diff --git a/.agents/skills/native-trigger/SKILL.md b/.agents/skills/native-trigger/SKILL.md index c30a02653b..d3d2a4f5bb 100644 --- a/.agents/skills/native-trigger/SKILL.md +++ b/.agents/skills/native-trigger/SKILL.md @@ -123,21 +123,22 @@ accounts) are many per service. Each trigger acts through one connection, named | Table | What's Stored | |-------|---------------| -| `workspace_integrations` | `oauth_data` JSON with `base_url`, `client_id`, `client_secret`, `instance_shared` flag and the workspace app's registered `redirect_uri`. One row per (workspace, service); it must exist for every connection made by the connect flow, since token refresh reads the client from it | +| `workspace_integrations` | `oauth_data` JSON with the workspace's own app: `base_url`, `client_id`, `client_secret` and its registered `redirect_uri`. NULL when the workspace has none and the row only holds the shared `resource_path`. Rows with `instance_shared` are legacy, kept for accounts made before connections went through the resource connect | | `variable` | Encrypted `access_token` at the connection path, linked to `account` via its `account` column | -| `account` | `refresh_token` and the requested `scopes`. The connect flow writes `client` = service name and `is_workspace_integration = true` | +| `account` | `refresh_token` and the requested `scopes`. A token issued by the workspace app has `client` = service name and `is_workspace_integration = true`; one issued by the instance connect client has `client` = resource type | | `resource` | The connection's resource at the same path, of the service's resource type, `{ "token": "$var:" }` | -Any resource of the service's resource type with a variable at the same path is a connection, -including one connected for runnables through the resource connect drawer. Its account -(`is_workspace_integration = false`) was issued by the instance connect client, so -`http_client_request` refreshes it through the variable store (`windmill_store`'s -`_refresh_token`), never with the workspace app. A connection whose account lacks some of -`ServiceName::oauth_scopes` reports them as `missing_scopes`; reconnecting asks for those plus the -account's own scopes. Only connections the connect flow made can be reconnected or disconnected -(`check_can_replace`, `delete_connection`): a connected resource's token may hold scopes its -runnables need that a trigger connect would not request (a GitHub resource has no account to -read them from), so its lifecycle stays in Resources. +A connection is any resource of the service's resource type with a variable at the same path, and +there is one way to make one: the resource connect drawer (`AppConnectInner.svelte`), opened from +Resources or the trigger picker with the service's `required_scopes` added. It connects through the +workspace's app when there is one (`generate_connect_url` and `callback` here, which only build the +authorize URL with a signed state and exchange the code), otherwise through the instance connect +client (`/oauth/connect/{client}`). Either way the drawer saves the token with `createAccount`. +`http_client_request` refreshes a workspace-app account with the workspace's client and any other +through the variable store (`windmill_store`'s `_refresh_token`). A connection whose account lacks +some of `ServiceName::oauth_scopes` reports them as `missing_scopes`. Reconnecting opens the drawer +on the existing path with those plus the account's own scopes, and `createAccount` with `replace` +swaps the token and account in place. A user may use a connection when they can read its variable (checked with a user transaction, so the variable's row-level security decides): `resolve_usable_connection` / @@ -164,10 +165,6 @@ pub struct OAuthConfig { A refreshed token is written back by connection path and account id, never by service: providers like Nextcloud rotate refresh tokens, so writing one onto another account breaks its next refresh. -Instance-level sharing: when the workspace has no OAuth app of its own and the instance admin -shares one (`share_with_workspaces` in the `oauths` setting; not available for Nextcloud), the -connect flow uses it and records `{"instance_shared": true}` in `workspace_integrations`. - ### URL Resolution The `resolve_endpoint()` helper handles both absolute and relative OAuth URLs: @@ -775,11 +772,21 @@ pub async fn prepare_native_trigger_args(service_name, db, w_id, headers, body) } ``` -### Instance-Level OAuth Credentials +### Instance and Workspace OAuth Clients -When `workspace_integrations.oauth_data.instance_shared == true`, `decrypt_oauth_data()` reads `client_id` and `client_secret` from instance-level global settings instead of workspace-level. This allows admins to share OAuth app credentials across workspaces. +Every workspace can connect through the instance's connect client for a service; there is no +per-workspace sharing switch. A workspace app, when configured, takes precedence in the resource +connect drawer. `workspace_integrations.oauth_data.instance_shared == true` only appears on rows +written before connections went through the resource connect: `decrypt_oauth_data()` then reads +`client_id` and `client_secret` from the instance settings to refresh those legacy accounts. -`generate_connect_url` picks the client (`resolve_oauth_client`): the workspace's own app when configured, the instance's otherwise. The server also picks the redirect URI (`redirect_uri_for`), identically when exchanging the code: `{BASE_URL}/oauth/callback/{resource_type}` for an instance client, which it already registers for resources; for a workspace app, the `redirect_uri` it was saved with, or `/workspace_settings?tab=native_triggers&service=` for one saved before that was stored. Every page a provider can send the user back to (that callback, `/user/login_callback/{client}`, the workspace settings page, the legacy `/oauth/callback/github/native_trigger`) recognises the signed state and hands it to `NativeOAuthCallback`, so a provider with a single registered URI per client (Nextcloud) works whichever one the admin registered. +For a workspace app the server picks the redirect URI (`redirect_uri_for`), identically when +exchanging the code: the `redirect_uri` it was saved with, or +`/workspace_settings?tab=native_triggers&service=` for one saved before that was stored. Every +page a provider can send the user back to (`/oauth/callback/{client}`, +`/user/login_callback/{client}`, the workspace settings page, the legacy +`/oauth/callback/github/native_trigger`) recognises the signed state and hands it to +`NativeOAuthCallback`, which exchanges the code and posts the token to the drawer that opened it. --- diff --git a/.github/workflows/frontend-check.yml b/.github/workflows/frontend-check.yml index 0a70c8dd05..7574096698 100644 --- a/.github/workflows/frontend-check.yml +++ b/.github/workflows/frontend-check.yml @@ -11,6 +11,8 @@ on: - "frontend/**" # The flow chat compiles the chat SDK's source in (svelte.config.js alias). - "chat-sdk/src/**" + # Also compiled in through an alias. + - "cli/windmill-utils-internal/src/**" - ".github/workflows/frontend-check.yml" jobs: diff --git a/.github/workflows/npm_on_release.yml b/.github/workflows/npm_on_release.yml index 8ebc38391a..0d07757959 100644 --- a/.github/workflows/npm_on_release.yml +++ b/.github/workflows/npm_on_release.yml @@ -51,3 +51,26 @@ jobs: with: bun-version: latest - run: cd cli && ./build.sh && cd npm && npm publish --access public + publish_utils_internal: + runs-on: ubuntu-latest + environment: npm + permissions: + contents: read + id-token: write + defaults: + run: + working-directory: cli/windmill-utils-internal + steps: + - uses: actions/checkout@v4.4.0 + - uses: actions/setup-node@v7.1.0 + with: + node-version: "24.x" + registry-url: "https://registry.npmjs.org" + # Versioned on its own, so most releases have nothing new to publish. + - run: | + pkg=$(node -p 'const p = require("./package.json"); p.name + "@" + p.version') + if [ -n "$(npm view "$pkg" version 2>/dev/null)" ]; then + echo "$pkg is already published" + else + npm ci && npm publish + fi diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 427fbc10c0..aa5035b0db 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.884.1" + ".": "1.894.1" } diff --git a/AGENTS.md b/AGENTS.md index c1ad3b7310..b1db387c12 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,7 +73,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 `` / `` 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 and by the token forms' Build and run access, 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`), and a member whose role cannot run is held to read-only, with no run tools (`session_ctx_with`, and `capabilitiesForRole` in the chat); the two copies of each 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` 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 and by the token forms' Build and run access, 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`), and a member whose role cannot run is held to read-only, with no run tools (`session_ctx_with`, and `capabilitiesForRole` in the chat); the two copies of each 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` view (`mcp/card.html`; bump `CARD_URI` in `mcp/session.rs` when what 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 no model reads. Their `structuredContent` only names the call (`{tool, workspace_id, arguments}`): Codex's and ChatGPT's models read `structuredContent`, so card data there would cost context on every show call, and Claude hands the card no `_meta`, so the card then loads the data with `load_card`, an app-only tool (`visibility: ["app"]`) no host lists to the model. 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 (`load_card` to draw, refresh and re-read a draft, `cancel_job`, `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`). The show tools are hidden from a client that declares capabilities without the MCP Apps extension on each request (`2026-07-28`); every other client gets them, with a text fallback (status, a short result, the link), because the sessionless server cannot see an older client's `initialize` capabilities. - **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/CHANGELOG.md b/CHANGELOG.md index 2e66471050..4504f2122d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,199 @@ # Changelog +## [1.894.1](https://github.com/windmill-labs/windmill/compare/v1.894.0...v1.894.1) (2026-12-01) + + +### Bug Fixes + +* run squashed loop iterations as regular jobs ([#12772](https://github.com/windmill-labs/windmill/issues/12772)) ([b4ca673](https://github.com/windmill-labs/windmill/commit/b4ca673a2920f20b283e59dd3afc9786ee741ff2)) + +## [1.894.0](https://github.com/windmill-labs/windmill/compare/v1.893.0...v1.894.0) (2026-11-30) + + +### Features + +* load a large result on request, ten render_all elements at a time ([#12664](https://github.com/windmill-labs/windmill/issues/12664)) ([d1abc75](https://github.com/windmill-labs/windmill/commit/d1abc75fa6afcf60ed1948830fb90d0a3c6ece94)) +* show s3 csv and parquet results in the db table with filters ([#12712](https://github.com/windmill-labs/windmill/issues/12712)) ([8064fa8](https://github.com/windmill-labs/windmill/commit/8064fa8fb62fc30ce88777395bf69ca828374e23)) + + +### Bug Fixes + +* copy labels into forks and detect label changes in compare ([#12738](https://github.com/windmill-labs/windmill/issues/12738)) ([f79e4b6](https://github.com/windmill-labs/windmill/commit/f79e4b618dee54f25396e5b70eef9cca05781cef)) +* forward ai proxy decisions requests on output-limited models ([#12770](https://github.com/windmill-labs/windmill/issues/12770)) ([39fb7f3](https://github.com/windmill-labs/windmill/commit/39fb7f34cb206a8087d2ca05c5e6a5c108302f44)) +* give AI agent tools run locally a job span and log fields ([#12684](https://github.com/windmill-labs/windmill/issues/12684)) ([d482968](https://github.com/windmill-labs/windmill/commit/d48296808effa9cb259adc891e9a6f8f4ee3b0ca)) +* resolve $var: references in custom ai resource headers ([#12764](https://github.com/windmill-labs/windmill/issues/12764)) ([a57f2df](https://github.com/windmill-labs/windmill/commit/a57f2df2c8b2e87d4ea329ab48ad2a0943b3d53c)) +* S3 table preview and DB table search bar bugs ([#12768](https://github.com/windmill-labs/windmill/issues/12768)) ([876fbb1](https://github.com/windmill-labs/windmill/commit/876fbb1e09c9723f80603abb4c759f4e4dbefe16)) +* show a running job with a fading play ring on home and the runs page ([#12671](https://github.com/windmill-labs/windmill/issues/12671)) ([e3d5b04](https://github.com/windmill-labs/windmill/commit/e3d5b043504e6292967bcac479703d54a7d6a0ee)) + +## [1.893.0](https://github.com/windmill-labs/windmill/compare/v1.892.0...v1.893.0) (2026-11-30) + + +### Features + +* configurable CRAN repository url for R scripts ([#12759](https://github.com/windmill-labs/windmill/issues/12759)) ([5b6ee10](https://github.com/windmill-labs/windmill/commit/5b6ee1001c0092576bd1e4de5c8bfdca9698aeca)) + + +### Bug Fixes + +* keep the cli login form reachable under a long admin reliance notice ([#12761](https://github.com/windmill-labs/windmill/issues/12761)) ([0a4583b](https://github.com/windmill-labs/windmill/commit/0a4583b661cf36a30c1059c36adaf45b5b6e6765)) + +## [1.892.0](https://github.com/windmill-labs/windmill/compare/v1.891.0...v1.892.0) (2026-11-30) + + +### Features + +* instance-wide IP allowlist on the Client IP settings page ([#12756](https://github.com/windmill-labs/windmill/issues/12756)) ([d62b195](https://github.com/windmill-labs/windmill/commit/d62b195f481c149dd20facaead07a92feda29d9f)) +* make client IP trust settable from the instance settings ([#12755](https://github.com/windmill-labs/windmill/issues/12755)) ([de14e74](https://github.com/windmill-labs/windmill/commit/de14e74ec0e0d461072e4c3ee21083abdec7705d)) + +## [1.891.0](https://github.com/windmill-labs/windmill/compare/v1.890.0...v1.891.0) (2026-11-29) + + +### Features + +* record the real client IP behind proxies with no configuration ([#12752](https://github.com/windmill-labs/windmill/issues/12752)) ([9039e1a](https://github.com/windmill-labs/windmill/commit/9039e1a8246f120beb353cca824bdefcefe31882)) + + +### Bug Fixes + +* **audit:** record what a global users.update changed (super_admin, devops, disabled, name) ([#12742](https://github.com/windmill-labs/windmill/issues/12742)) ([ca1cb13](https://github.com/windmill-labs/windmill/commit/ca1cb13ad9c349413bd8cff26ebe694595f1f0cf)) + +## [1.890.0](https://github.com/windmill-labs/windmill/compare/v1.889.1...v1.890.0) (2026-11-29) + + +### Features + +* show what a token loses without its owner's admin rights ([#12749](https://github.com/windmill-labs/windmill/issues/12749)) ([3ee1d6a](https://github.com/windmill-labs/windmill/commit/3ee1d6a4b8ce56209f0617d1cbd67951ea6df0c5)) + + +### Bug Fixes + +* clearer refusal messages and an install-scripts opt-in for app bundling ([#12750](https://github.com/windmill-labs/windmill/issues/12750)) ([6ca1820](https://github.com/windmill-labs/windmill/commit/6ca1820c518bcf684d3b31231a3f4109e9b390d7)) +* **cli:** accept the cwd's spelling of the checkout in wmill dev path checks ([#12736](https://github.com/windmill-labs/windmill/issues/12736)) ([76ac275](https://github.com/windmill-labs/windmill/commit/76ac275686d348a6ad61b470cc909e72305a80a7)) +* consistent argument reference handling across captures, re-runs, approvals and evals ([#12745](https://github.com/windmill-labs/windmill/issues/12745)) ([86612a0](https://github.com/windmill-labs/windmill/commit/86612a0ff609013027e69f6f3839cbba56675a05)) +* consistent writes for linked resource/variable pairs and instance database resolution ([#12746](https://github.com/windmill-labs/windmill/issues/12746)) ([09202d4](https://github.com/windmill-labs/windmill/commit/09202d40948d59fc3e519a103c55ce8a7b04669b)) +* copy data tables whose database uses extensions ([#12716](https://github.com/windmill-labs/windmill/issues/12716)) ([2a53334](https://github.com/windmill-labs/windmill/commit/2a53334b3ffe7de5a22d57e951a9eb7487d47f8f)) +* leave draining workers out of the autoscaling count ([#12739](https://github.com/windmill-labs/windmill/issues/12739)) ([dd206df](https://github.com/windmill-labs/windmill/commit/dd206df8e33aa7ba6adc4e04c4dd56696f16338c)) +* resolve runnables and run-as identities consistently across tasks, deploys and triggers ([#12744](https://github.com/windmill-labs/windmill/issues/12744)) ([8fac722](https://github.com/windmill-labs/windmill/commit/8fac722b8edfce2ae29fc9a8723d8d0e4faf9ff5)) +* tighten generated SQL names, flow input lookup and app install steps ([#12748](https://github.com/windmill-labs/windmill/issues/12748)) ([65d567f](https://github.com/windmill-labs/windmill/commit/65d567fec6468dcbb2d52528b4594fe4a0c26b59)) +* tighten token scope consistency across MCP, job import and capture paths ([#12743](https://github.com/windmill-labs/windmill/issues/12743)) ([3ee0d88](https://github.com/windmill-labs/windmill/commit/3ee0d889ef7d1453666c3c451be9259da3c8825b)) +* workspace and fork lifecycle consistency ([#12747](https://github.com/windmill-labs/windmill/issues/12747)) ([0f2f8aa](https://github.com/windmill-labs/windmill/commit/0f2f8aaaa325b93a42c78753a9b4184f3670763e)) + +## [1.889.1](https://github.com/windmill-labs/windmill/compare/v1.889.0...v1.889.1) (2026-11-28) + + +### Bug Fixes + +* **frontend:** keep url helpers in their own chunk ([dde36c1](https://github.com/windmill-labs/windmill/commit/dde36c16826ce534ff3d4e0c403e373394693149)) +* read scope for listing mcp tools ([8ccb60c](https://github.com/windmill-labs/windmill/commit/8ccb60c711ada9abdb46e9afa24760bb899bdd89)) + +## [1.889.0](https://github.com/windmill-labs/windmill/compare/v1.888.0...v1.889.0) (2026-11-28) + + +### Features + +* **mcp:** show client details on the oauth consent page ([1a43ff8](https://github.com/windmill-labs/windmill/commit/1a43ff85005fb972404323decab3bbbf61f8cb2b)) + + +### Bug Fixes + +* app rendering mode for visitors ([24b15a7](https://github.com/windmill-labs/windmill/commit/24b15a72e846a648ce52f50f9d7141a1aff8ad52)) +* **cli:** dev server and sync path handling improvements ([46a64b1](https://github.com/windmill-labs/windmill/commit/46a64b1b467b9596e698456abf38369744dd8843)) +* **frontend:** dev page and raw app editor message handling ([c883b82](https://github.com/windmill-labs/windmill/commit/c883b82fa73a4a6556cebe4b0ef72d2923d8046b)) +* **frontend:** input handling cleanups ([90c1361](https://github.com/windmill-labs/windmill/commit/90c1361b73f8897a4dce78f1b59163df4027a3ea)) +* **frontend:** use the shared markdown renderer in more views ([767d2d6](https://github.com/windmill-labs/windmill/commit/767d2d6f915db277a3e712e3a0075924a17aadbb)) +* recordings and mcp tools loading tweaks ([b9e0e06](https://github.com/windmill-labs/windmill/commit/b9e0e068788681a24748f28b4af2df9a3c7e7998)) +* serve s3 previews with an explicit content type ([#12715](https://github.com/windmill-labs/windmill/issues/12715)) ([4f309ec](https://github.com/windmill-labs/windmill/commit/4f309ec5fb01d13636a4bcef7fd1fe427a307823)) +* tidy redirect handling after login and logout ([561c5a1](https://github.com/windmill-labs/windmill/commit/561c5a1ad30b3c34c8c7d42008f57645078e9854)) +* token scope matching cleanups ([7365bfd](https://github.com/windmill-labs/windmill/commit/7365bfdf68a3cdb42c25f6a0b7053eec22f64752)) +* **typescript-client:** read task parameter names past a default value ([#12718](https://github.com/windmill-labs/windmill/issues/12718)) ([a7ee99c](https://github.com/windmill-labs/windmill/commit/a7ee99ce63671efde8860e89b3ead8cf794c1c9f)) +* **typescript-client:** skip regex literals when reading task parameter names ([00acb80](https://github.com/windmill-labs/windmill/commit/00acb80e0dfe803c7741f63b380bf95f33605f8f)) + +## [1.888.0](https://github.com/windmill-labs/windmill/compare/v1.887.0...v1.888.0) (2026-11-28) + + +### Features + +* open images in the session preview panel ([#12602](https://github.com/windmill-labs/windmill/issues/12602)) ([0c63dfe](https://github.com/windmill-labs/windmill/commit/0c63dfe18cdcd86cd34cc51907ceef2118e80e2f)) +* require two-factor authentication for password logins ([#12704](https://github.com/windmill-labs/windmill/issues/12704)) ([8ec6bee](https://github.com/windmill-labs/windmill/commit/8ec6beed3a4ef550ecd86991122b8a8757ef7021)) + + +### Bug Fixes + +* give mcp show tools a text fallback for clients without cards ([#12707](https://github.com/windmill-labs/windmill/issues/12707)) ([84e9038](https://github.com/windmill-labs/windmill/commit/84e903848af65ca049d8059c9627a859220052b2)) +* **mcp:** hold each MCP call to its own token, workspace and route ([#12709](https://github.com/windmill-labs/windmill/issues/12709)) ([cb5d6a9](https://github.com/windmill-labs/windmill/commit/cb5d6a92c22bdb606c23266a7370d726ef9eb16e)) +* opt the audit probe token into superadmin ([#12710](https://github.com/windmill-labs/windmill/issues/12710)) ([3ad867e](https://github.com/windmill-labs/windmill/commit/3ad867ee658a9bf9aa7c587d4e61724915841683)) +* tidy the mcp show tool text fallbacks ([#12713](https://github.com/windmill-labs/windmill/issues/12713)) ([a32ae57](https://github.com/windmill-labs/windmill/commit/a32ae571ca3bdae708f8018abd193d45de69241d)) +* validate return addresses on the webhook and cli sign-in pages ([#12719](https://github.com/windmill-labs/windmill/issues/12719)) ([dce05fd](https://github.com/windmill-labs/windmill/commit/dce05fdc3b775d9930b17fdfc3eeb8c93fb389a4)) + +## [1.887.0](https://github.com/windmill-labs/windmill/compare/v1.886.0...v1.887.0) (2026-11-27) + + +### Features + +* add native totp two-factor authentication for password login ([#12620](https://github.com/windmill-labs/windmill/issues/12620)) ([f52c117](https://github.com/windmill-labs/windmill/commit/f52c117e76c4b39265e4d5b3f8304934dce3f0c0)) +* add token introspection endpoint and token test UI ([#12702](https://github.com/windmill-labs/windmill/issues/12702)) ([55aec82](https://github.com/windmill-labs/windmill/commit/55aec82102bca445fa91a2d6b926a8a68f953527)) +* connect native trigger accounts through the resource connect flow ([#12352](https://github.com/windmill-labs/windmill/issues/12352)) ([9643ba0](https://github.com/windmill-labs/windmill/commit/9643ba09a4c2a10172e2b4227f9c00f8c46662f5)) +* edit token expiration and allowed IPs, widen only as far as mintable ([#12703](https://github.com/windmill-labs/windmill/issues/12703)) ([b2f3986](https://github.com/windmill-labs/windmill/commit/b2f3986f9430147eab8fb36d47c091124824de0e)) +* edit token scopes from the CLI and show token access in token lists ([#12694](https://github.com/windmill-labs/windmill/issues/12694)) ([7e79229](https://github.com/windmill-labs/windmill/commit/7e79229aa4731cf0fbf108ab946fa6b7b651d5d5)) +* flag risky tokens and add a superadmin token review ([#12693](https://github.com/windmill-labs/windmill/issues/12693)) ([51e9017](https://github.com/windmill-labs/windmill/commit/51e9017c67481e334c529387db442be2002a287c)) +* make new tokens workspace-bound and rights-free unless opted in ([#12695](https://github.com/windmill-labs/windmill/issues/12695)) ([f5644d7](https://github.com/windmill-labs/windmill/commit/f5644d7f431f7c566302645fd2e0e94970ea3376)) +* split account settings into profile, tokens, AI and MCP drawers ([#12691](https://github.com/windmill-labs/windmill/issues/12691)) ([46cf750](https://github.com/windmill-labs/windmill/commit/46cf7509fabb8464a75d5651b2ef6c0be83d81a4)) +* stop a loop once a failure threshold of iterations has failed ([#12686](https://github.com/windmill-labs/windmill/issues/12686)) ([0496abb](https://github.com/windmill-labs/windmill/commit/0496abbad8e494b6ae2eff0d72661c6b9534b179)) + + +### Bug Fixes + +* apply token read-only flag to HTTP route calls ([#12690](https://github.com/windmill-labs/windmill/issues/12690)) ([f1edefa](https://github.com/windmill-labs/windmill/commit/f1edefa132b6b5a7e6ba9475749027aa315895d3)) +* **cli:** accept Windows separators in strict-folder-boundaries test ([#12689](https://github.com/windmill-labs/windmill/issues/12689)) ([443ea15](https://github.com/windmill-labs/windmill/commit/443ea155a155dd2e76d7583b0ba48e6cd15d788c)) +* copy the shown error from AI chat tool cards ([#12698](https://github.com/windmill-labs/windmill/issues/12698)) ([5b3a40b](https://github.com/windmill-labs/windmill/commit/5b3a40b1a428a508b3472b1756a37cea33e869ef)) +* demote a token's superadmin when its owner loses it ([#12692](https://github.com/windmill-labs/windmill/issues/12692)) ([3ec14c7](https://github.com/windmill-labs/windmill/commit/3ec14c7ed2b1ff1283c69197522a5b79e3970a77)) +* **frontend:** open non-raster images in a new tab as PNG ([#12697](https://github.com/windmill-labs/windmill/issues/12697)) ([de2cd55](https://github.com/windmill-labs/windmill/commit/de2cd55b338d48de055f134e304dfbe10c3ca29e)) +* rerun recovered iterations in failed-only restarts ([#12657](https://github.com/windmill-labs/windmill/issues/12657)) ([57ad72b](https://github.com/windmill-labs/windmill/commit/57ad72b28aaf9386eb552443379addb7d3b00777)) + +## [1.886.0](https://github.com/windmill-labs/windmill/compare/v1.885.0...v1.886.0) (2026-11-26) + + +### Features + +* a second OTel logs exporter for audit logs ([#12675](https://github.com/windmill-labs/windmill/issues/12675)) ([f28bdff](https://github.com/windmill-labs/windmill/commit/f28bdff94f82d18c2d75d179c6f35f524f5b220c)) +* add a Require SSO workspace protection rule ([#12681](https://github.com/windmill-labs/windmill/issues/12681)) ([71f22fc](https://github.com/windmill-labs/windmill/commit/71f22fc6e93f43b2ee4d1eec5c1b5c9ece5e941e)) +* overwrite or discard each path conflict when reassigning user items ([#12683](https://github.com/windmill-labs/windmill/issues/12683)) ([b3ab8e2](https://github.com/windmill-labs/windmill/commit/b3ab8e22b37a666d4ffdbead4a80c406502254b2)) +* own model and effort for script generation and AI review ([#12678](https://github.com/windmill-labs/windmill/issues/12678)) ([51cd51c](https://github.com/windmill-labs/windmill/commit/51cd51cd52cabed72b6516e83b1542d0225543cd)) +* record client IP and user agent on audit entries ([#12673](https://github.com/windmill-labs/windmill/issues/12673)) ([c689d74](https://github.com/windmill-labs/windmill/commit/c689d74505a007d87dfc558fd69ee22ccba22653)) + + +### Bug Fixes + +* derive the client ip from trusted proxies only ([#12677](https://github.com/windmill-labs/windmill/issues/12677)) ([f452090](https://github.com/windmill-labs/windmill/commit/f45209064ac3a030e0c31f5ac54c09f8c54a32c1)) +* redact secrets in instance settings reads unless explicitly revealed ([#12682](https://github.com/windmill-labs/windmill/issues/12682)) ([cc855e6](https://github.com/windmill-labs/windmill/commit/cc855e6fd94268c19bf05658736e15b83310f283)) +* resolve the client ip in one place and trust private ranges only on cloud ([#12685](https://github.com/windmill-labs/windmill/issues/12685)) ([0b11d3e](https://github.com/windmill-labs/windmill/commit/0b11d3e9a691450997d902015f680a54fd2f2cc6)) + +## [1.885.0](https://github.com/windmill-labs/windmill/compare/v1.884.1...v1.885.0) (2026-11-25) + + +### Features + +* hand the code selected with ⌘K and Ctrl+L to an AI session ([#12661](https://github.com/windmill-labs/windmill/issues/12661)) ([5d4820d](https://github.com/windmill-labs/windmill/commit/5d4820d3736fa6f307fb4838e525e32c4dc24838)) +* pass MCP image results to the AI chat model as images ([#12660](https://github.com/windmill-labs/windmill/issues/12660)) ([772c0c3](https://github.com/windmill-labs/windmill/commit/772c0c30f1f47a84b2fd7ec6456882482c0759c5)) +* show who approved a flow run, and list opted-in approvals on home ([#12604](https://github.com/windmill-labs/windmill/issues/12604)) ([3efe1e9](https://github.com/windmill-labs/windmill/commit/3efe1e97a7d54be674b78dbfdb48e6f8f8591527)) +* show why a step waits: sleep, concurrency limit, approval ([#12607](https://github.com/windmill-labs/windmill/issues/12607)) ([182356e](https://github.com/windmill-labs/windmill/commit/182356ec358cf9fa759983d39ffff128468c85cb)) + + +### Bug Fixes + +* bound sqlx's return-to-pool step so a failover can't wedge the pool ([#12655](https://github.com/windmill-labs/windmill/issues/12655)) ([8e3f117](https://github.com/windmill-labs/windmill/commit/8e3f11705f8705e2c1adb50a139b4a501795e5ec)) +* check run scope on what a schedule or trigger save names ([#12618](https://github.com/windmill-labs/windmill/issues/12618)) ([4b715c4](https://github.com/windmill-labs/windmill/commit/4b715c422a75e93ac9a6aa9b9c74a31ba786734c)) +* **cli:** keep generate-metadata inside the named folder ([#12668](https://github.com/windmill-labs/windmill/issues/12668)) ([2c2273c](https://github.com/windmill-labs/windmill/commit/2c2273cffb26c55e883bad6ee96653935e0412ab)) +* hold a volume's lease through sync-back and pull it in parallel ([#12667](https://github.com/windmill-labs/windmill/issues/12667)) ([5953595](https://github.com/windmill-labs/windmill/commit/5953595d50a20fc08449bf1d0c7aa6b0c0a12b81)) +* let the attached flow step panel scroll ([#12652](https://github.com/windmill-labs/windmill/issues/12652)) ([29383dd](https://github.com/windmill-labs/windmill/commit/29383dd814677465f98a02038b2fd2d83e117edd)) +* log in on the live session when the browser sends two token cookies ([#12663](https://github.com/windmill-labs/windmill/issues/12663)) ([8f637d5](https://github.com/windmill-labs/windmill/commit/8f637d58d6654740bca41f32a3462e5951ff8f4c)) +* match flow step pickers to the role and keep picked settings ([#12654](https://github.com/windmill-labs/windmill/issues/12654)) ([00e354d](https://github.com/windmill-labs/windmill/commit/00e354dade598ed9f434576ef616b53e0cf6b543)) +* **mcp:** require a session on the MCP OAuth client routes and audit registrations ([#12647](https://github.com/windmill-labs/windmill/issues/12647)) ([2b7c7e9](https://github.com/windmill-labs/windmill/commit/2b7c7e98acfc96dc10931948252a02d39325e798)) +* **python:** treat tomllib and newer stdlib modules as stdlib in import inference ([#12670](https://github.com/windmill-labs/windmill/issues/12670)) ([655562e](https://github.com/windmill-labs/windmill/commit/655562e805a9b74adbb1e3faa85d97bc567dd99a)) +* show minutes instead of seconds after the first minute in relative times ([#12631](https://github.com/windmill-labs/windmill/issues/12631)) ([b59d27b](https://github.com/windmill-labs/windmill/commit/b59d27bdb1daaa0e3fbacc3cfb692b01fe7254d3)) +* skip the session backup in preview frames and keep draft handles stable ([#12598](https://github.com/windmill-labs/windmill/issues/12598)) ([53ebb94](https://github.com/windmill-labs/windmill/commit/53ebb94ddb167ae4bebd06fcdbed77df1391bc68)) +* stop state_snapshot_uncloneable warnings from chart options ([#12653](https://github.com/windmill-labs/windmill/issues/12653)) ([2bdad42](https://github.com/windmill-labs/windmill/commit/2bdad42ad060e5678df22e5df3d90d598c2586c5)) + ## [1.884.1](https://github.com/windmill-labs/windmill/compare/v1.884.0...v1.884.1) (2026-11-25) diff --git a/Caddyfile b/Caddyfile index 3008c93855..a207e50960 100644 --- a/Caddyfile +++ b/Caddyfile @@ -1,4 +1,11 @@ { + # Caddy replaces X-Forwarded-For with its own peer unless that peer is trusted. With a load + # balancer or Cloudflare in front of Caddy, list its ranges so the client address reaches + # Windmill. On windmill_server, add a balancer to TRUSTED_PROXIES, but for Cloudflare set + # TRUST_CLOUDFLARE=true rather than listing its ranges, which any Cloudflare Worker sends from: + # servers { + # trusted_proxies static private_ranges + # } layer4 { :25 { route { diff --git a/Dockerfile b/Dockerfile index 32afc8347f..5a23fad6d7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -83,6 +83,8 @@ COPY /backend/windmill-api/build_openapi.sh /backend/windmill-api/build_openapi. COPY /system_prompts/auto-generated /system_prompts/auto-generated # The flow chat imports the chat SDK's source (svelte.config.js alias `windmill-chat`). COPY /chat-sdk/src /chat-sdk/src +# Shared with the CLI (svelte.config.js alias `windmill-utils-internal`). +COPY /cli/windmill-utils-internal/src /cli/windmill-utils-internal/src RUN cd /backend/windmill-api && . ./build_openapi.sh COPY /backend/parsers/windmill-parser-wasm/pkg/ /backend/parsers/windmill-parser-wasm/pkg/ diff --git a/REVIEW.md b/REVIEW.md index 21f5e50f26..f240fa4ea7 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -30,6 +30,18 @@ If the prompt context provides a `PR AUTHOR` (GitHub login) and the verdict is N - Read additional files only when the diff is not enough to validate a finding. - Do not modify any files. +## Accepted risks + +Some security trade-offs are decided on purpose and recorded where the code they concern is +documented. Do not report them as findings; do report a change that widens one beyond what its +record describes. + +- **Client IP default proxy trust** (`backend/windmill-common/src/client_ip.rs`, + `docs/auth-surface.md` → "The client IP"): with `TRUSTED_PROXIES` unset, the private ranges are + trusted as proxies, token IP allowlists included, so a host on the private network can name its + own client address. Setting `TRUSTED_PROXIES` to the actual proxies' addresses (not `private`) + closes it. + ## Severity triage Tag each finding with a severity. Always report P0 and P1. Report P2 only when the diff invites it (a new `pub fn`, a new module, a new exported component, a meaningful refactor). diff --git a/ai_evals/README.md b/ai_evals/README.md index 3c123e2579..824354a257 100644 --- a/ai_evals/README.md +++ b/ai_evals/README.md @@ -254,6 +254,22 @@ secretRequests: and the resource are created in the workspace, deployed, and the model reads the result the chat would give it. `check` is reported as is; no connection test runs. +`runtime.codeSelections` attaches code to the prompt of a global case, as the chips of code +selected in an editor do. `source` names the item (`script`, `flow`, `raw_app` or `agent`) and +optionally its `part` (a flow step, app runnable, agent tool or script module file), and +`content` is the code from `startLine` to `endLine`: + +```yaml +codeSelections: + - source: { kind: flow, path: f/evals/global/process_refund, part: calculate_total } + lang: bun + startLine: 1 + endLine: 2 + content: |- + export async function main(subtotal: number) { + return { subtotal, total: subtotal } +``` + `runtime.profile` runs a session-chat case (`sessionChat: true`) as a non-admin role instead of full access: the prompt, toolset and tool schemas are cut as production's `capabilitiesForRole` cuts them, and the workspace's `operator_settings` are seeded for the diff --git a/ai_evals/adapters/frontend/core/global/globalEvalRunner.ts b/ai_evals/adapters/frontend/core/global/globalEvalRunner.ts index f3d025626c..c7b6080d59 100644 --- a/ai_evals/adapters/frontend/core/global/globalEvalRunner.ts +++ b/ai_evals/adapters/frontend/core/global/globalEvalRunner.ts @@ -4,6 +4,7 @@ import { globalToolsFor, prepareGlobalUserMessage, } from "../../../../../frontend/src/lib/components/copilot/chat/global/core"; +import { createCodeSelection } from "../../../../../frontend/src/lib/components/copilot/chat/context"; import { assembleGlobalSystemMessage } from "../../../../../frontend/src/lib/components/copilot/chat/global/globalAssembly"; import { canBuild, @@ -46,6 +47,7 @@ import { type EvalPreviewTabFixture, } from "./evalPreviewTabs"; import type { + EvalCaseCodeSelection, EvalCaseProfile, EvalSecretRequestAnswer, ModeRunContext, @@ -145,6 +147,7 @@ export interface GlobalEvalOptions { // Start in plan mode: the gate refuses every tool without `planModeSafe`, and the two plan // tools are offered. Needs sessionChat, which is what plan mode is gated on in production. planMode?: boolean; + codeSelections?: EvalCaseCodeSelection[]; // The user's rights, resolved as a session resolves them; unset keeps full access. profile?: EvalCaseProfile; // Run the pipeline the chat drafted once it is over (`validate.pipelineRun`). @@ -286,6 +289,9 @@ export async function runGlobalEval( pipelineFolders: pipelineEditors?.folders(), }); const baseSystemMessage = assembleSystemMessage(); + const codeSelections = (options.codeSelections ?? []).map(({ source, ...selection }) => + createCodeSelection(source, selection), + ); const helpers = { ...evalArtifacts.helpers, // A standalone chat has no session: the tools that behave differently in one (a pipeline @@ -317,7 +323,7 @@ export async function runGlobalEval( isToolAvailable: (name) => (!pipelineToolNames.has(name) || (pipelineEditors?.folders().length ?? 0) > 0) && (planMode?.isToolAvailable?.(name) ?? true), - userMessage: prepareGlobalUserMessage(userPrompt, [], { + userMessage: prepareGlobalUserMessage(userPrompt, codeSelections, { ...(injectActiveEditorContext ? { workspace: workspaceRoot } : {}), activePreview: panel?.activePreview(), resourceTypeSync: await resolveResourceTypeSync(workspaceRoot, []), diff --git a/ai_evals/cases/global.yaml b/ai_evals/cases/global.yaml index 1976004840..a5093b3409 100644 --- a/ai_evals/cases/global.yaml +++ b/ai_evals/cases/global.yaml @@ -519,6 +519,45 @@ - returns subtotal, tax, and total from the updated flow logic - leaves the result as a draft only +- id: global-code-selection-names-its-item + prompt: |- + Throw an error here when the subtotal is negative. + Keep the change as a draft. + initial: ai_evals/fixtures/frontend/global/initial/current_invoice_live_flow.json + runtime: + maxTurns: 10 + codeSelections: + - source: + kind: flow + path: f/evals/global/process_refund + part: calculate_total + lang: bun + startLine: 1 + endLine: 2 + content: |- + export async function main(subtotal: number) { + return { subtotal, total: subtotal } + validate: + # The open flow's own draft, which must stay as it was, and the edited one. + draftCountExactly: 2 + requiredDrafts: + - type: flow + path: f/evals/global/process_refund + valueIncludes: + - calculate_total + - throw + forbiddenDrafts: + - type: flow + path: f/evals/global/process_invoice + toolExpect: + forbiddenToolsUsed: + - deploy_workspace_item + - delete_workspace_item + judgeChecklist: + - edits the calculate_total step of the process_refund flow, which the selected code belongs to, not the flow open in the editor + - throws when the subtotal is negative and keeps the rest of the step as it was + - leaves the result as a draft only + - id: global-test14-current-without-live-editor-asks-question prompt: |- Please update this script so it returns `ok`. diff --git a/ai_evals/core/types.ts b/ai_evals/core/types.ts index 7caa2d5fb8..e9e4d0cede 100644 --- a/ai_evals/core/types.ts +++ b/ai_evals/core/types.ts @@ -38,6 +38,8 @@ export interface EvalCaseRuntimeSpec { secretRequests?: EvalSecretRequestAnswer[]; backendPreview?: EvalCaseRuntimeBackendPreview; appContext?: EvalCaseRuntimeAppContextSpec; + // Global mode: code the user selected in an editor and attached to the prompt. + codeSelections?: EvalCaseCodeSelection[]; // Global mode: run as a session chat (preview tools + session prompt) vs the standalone chat. sessionChat?: boolean; // Global session chats: start the case in plan mode, so the workspace-changing tools are @@ -60,6 +62,14 @@ export interface EvalSecretRequestAnswer { check?: { ok: true } | { ok: false; error: string }; } +export interface EvalCaseCodeSelection { + source: { kind: "script" | "flow" | "raw_app" | "agent"; path: string; part?: string }; + lang: "bun" | "python3" | "bash" | "postgresql"; + startLine: number; + endLine: number; + content: string; +} + export interface EvalCaseProfile { operator: boolean; operatorSettings?: { diff --git a/ai_evals/modes/global.ts b/ai_evals/modes/global.ts index 71d4dae1da..cabed79045 100644 --- a/ai_evals/modes/global.ts +++ b/ai_evals/modes/global.ts @@ -55,6 +55,7 @@ export function createGlobalModeRunner( previewTabs: initial?.previewTabs, sessionChat: context.evalCase?.runtime?.sessionChat, planMode: context.evalCase?.runtime?.planMode, + codeSelections: context.evalCase?.runtime?.codeSelections, profile: context.evalCase?.runtime?.profile, pipelineRun: context.executionOnly ? undefined diff --git a/backend/.sqlx/query-027dbff1397b96a6fb1cfe9aaaffe226bf276cac01b052dac82a6e21b00ac833.json b/backend/.sqlx/query-027dbff1397b96a6fb1cfe9aaaffe226bf276cac01b052dac82a6e21b00ac833.json new file mode 100644 index 0000000000..446ec94a16 --- /dev/null +++ b/backend/.sqlx/query-027dbff1397b96a6fb1cfe9aaaffe226bf276cac01b052dac82a6e21b00ac833.json @@ -0,0 +1,80 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT email, label, token_prefix AS \"token_prefix!\", expiration,\n created_at AS \"created_at!\", last_used_at AS \"last_used_at!\", scopes, workspace_id,\n read_only AS \"read_only!\", risks AS \"risks!\"\n FROM token_risk\n WHERE NOT self_managed\n AND CASE WHEN $1::text IS NULL THEN cardinality(risks) > 0\n WHEN $1 = 'all' THEN true\n ELSE $1 = ANY(risks) END\n AND ($2::text IS NULL OR strpos(lower(email), $2) > 0\n OR strpos(lower(COALESCE(label, '')), $2) > 0)\n AND ($3::timestamptz IS NULL OR (last_used_at, token_prefix) > ($3, $4::text))\n ORDER BY last_used_at, token_prefix\n LIMIT $5", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "label", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "token_prefix!", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "expiration", + "type_info": "Timestamptz" + }, + { + "ordinal": 4, + "name": "created_at!", + "type_info": "Timestamptz" + }, + { + "ordinal": 5, + "name": "last_used_at!", + "type_info": "Timestamptz" + }, + { + "ordinal": 6, + "name": "scopes", + "type_info": "TextArray" + }, + { + "ordinal": 7, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 8, + "name": "read_only!", + "type_info": "Bool" + }, + { + "ordinal": 9, + "name": "risks!", + "type_info": "TextArray" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Timestamptz", + "Text", + "Int8" + ] + }, + "nullable": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ] + }, + "hash": "027dbff1397b96a6fb1cfe9aaaffe226bf276cac01b052dac82a6e21b00ac833" +} diff --git a/backend/.sqlx/query-0361abb4ab7e9a9cf28f0e0551892334eda482fea471e77b6febcd061feba08f.json b/backend/.sqlx/query-0361abb4ab7e9a9cf28f0e0551892334eda482fea471e77b6febcd061feba08f.json new file mode 100644 index 0000000000..6405fdd4fb --- /dev/null +++ b/backend/.sqlx/query-0361abb4ab7e9a9cf28f0e0551892334eda482fea471e77b6febcd061feba08f.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT key, original_scheduled_for IS NOT NULL AND released_at IS NULL AS \"held!\"\n FROM concurrency_key WHERE job_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "key", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "held!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + null + ] + }, + "hash": "0361abb4ab7e9a9cf28f0e0551892334eda482fea471e77b6febcd061feba08f" +} diff --git a/backend/.sqlx/query-05d2b07dd15d14a9c36bdb3dac87d1deb52b91ac98fdadc0c355955a1d90d26a.json b/backend/.sqlx/query-05d2b07dd15d14a9c36bdb3dac87d1deb52b91ac98fdadc0c355955a1d90d26a.json new file mode 100644 index 0000000000..e896c247ba --- /dev/null +++ b/backend/.sqlx/query-05d2b07dd15d14a9c36bdb3dac87d1deb52b91ac98fdadc0c355955a1d90d26a.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE password SET totp_recovery_codes = $2 WHERE email = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "TextArray" + ] + }, + "nullable": [] + }, + "hash": "05d2b07dd15d14a9c36bdb3dac87d1deb52b91ac98fdadc0c355955a1d90d26a" +} diff --git a/backend/.sqlx/query-08cc5c57fb76a392fc32c9122e32d8c33945f8e20daf9242e1de8f4f4ef5546e.json b/backend/.sqlx/query-08cc5c57fb76a392fc32c9122e32d8c33945f8e20daf9242e1de8f4f4ef5546e.json new file mode 100644 index 0000000000..1ac535026a --- /dev/null +++ b/backend/.sqlx/query-08cc5c57fb76a392fc32c9122e32d8c33945f8e20daf9242e1de8f4f4ef5546e.json @@ -0,0 +1,47 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT totp_secret, totp_pending_secret, totp_last_step, totp_recovery_codes,\n (totp_failed_attempts >= $2 AND totp_failed_since > now() - interval '1 minute')\n AS \"locked!\"\n FROM password WHERE email = $1 FOR UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "totp_secret", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "totp_pending_secret", + "type_info": "Text" + }, + { + "ordinal": 2, + "name": "totp_last_step", + "type_info": "Int8" + }, + { + "ordinal": 3, + "name": "totp_recovery_codes", + "type_info": "TextArray" + }, + { + "ordinal": 4, + "name": "locked!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Int4" + ] + }, + "nullable": [ + true, + true, + true, + true, + null + ] + }, + "hash": "08cc5c57fb76a392fc32c9122e32d8c33945f8e20daf9242e1de8f4f4ef5546e" +} diff --git a/backend/.sqlx/query-0cdcf2f56b35f2c4929071933c2c7f3e4e2dda9f0663fb8b814ce78c3c99a63d.json b/backend/.sqlx/query-0cdcf2f56b35f2c4929071933c2c7f3e4e2dda9f0663fb8b814ce78c3c99a63d.json new file mode 100644 index 0000000000..a1119618b7 --- /dev/null +++ b/backend/.sqlx/query-0cdcf2f56b35f2c4929071933c2c7f3e4e2dda9f0663fb8b814ce78c3c99a63d.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE password SET totp_secret = totp_pending_secret, totp_pending_secret = NULL,\n totp_recovery_codes = $2\n WHERE email = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "TextArray" + ] + }, + "nullable": [] + }, + "hash": "0cdcf2f56b35f2c4929071933c2c7f3e4e2dda9f0663fb8b814ce78c3c99a63d" +} diff --git a/backend/.sqlx/query-f5946a3968df859f668d6197562c10024ffc24f108ca48d5b3fa98e489d931ea.json b/backend/.sqlx/query-123015f4012169763ac8b16c2e4e0775b6da84dd53aeca8fb9b556f969aee29a.json similarity index 60% rename from backend/.sqlx/query-f5946a3968df859f668d6197562c10024ffc24f108ca48d5b3fa98e489d931ea.json rename to backend/.sqlx/query-123015f4012169763ac8b16c2e4e0775b6da84dd53aeca8fb9b556f969aee29a.json index ca7a719231..cb94c5045b 100644 --- a/backend/.sqlx/query-f5946a3968df859f668d6197562c10024ffc24f108ca48d5b3fa98e489d931ea.json +++ b/backend/.sqlx/query-123015f4012169763ac8b16c2e4e0775b6da84dd53aeca8fb9b556f969aee29a.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE volume\n SET size_bytes = $3, file_count = $4,\n updated_at = now(), last_used_at = now(),\n lease_until = NULL, leased_by = NULL,\n generation = generation + generation % 2\n WHERE workspace_id = $1 AND name = $2 AND leased_by = $5", + "query": "UPDATE volume\n SET size_bytes = $3, file_count = $4,\n updated_at = now(), last_used_at = now(),\n generation = generation + generation % 2\n WHERE workspace_id = $1 AND name = $2 AND leased_by = $5", "describe": { "columns": [], "parameters": { @@ -14,5 +14,5 @@ }, "nullable": [] }, - "hash": "f5946a3968df859f668d6197562c10024ffc24f108ca48d5b3fa98e489d931ea" + "hash": "123015f4012169763ac8b16c2e4e0775b6da84dd53aeca8fb9b556f969aee29a" } diff --git a/backend/.sqlx/query-134c3b21135ff0558fd234490b7ef56ccb86c2ba94d318c5fb341aa9114b8268.json b/backend/.sqlx/query-134c3b21135ff0558fd234490b7ef56ccb86c2ba94d318c5fb341aa9114b8268.json new file mode 100644 index 0000000000..28987c7d5f --- /dev/null +++ b/backend/.sqlx/query-134c3b21135ff0558fd234490b7ef56ccb86c2ba94d318c5fb341aa9114b8268.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE password SET totp_pending_secret = $2\n WHERE email = $1 AND login_type = 'password' AND totp_secret IS NULL", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "134c3b21135ff0558fd234490b7ef56ccb86c2ba94d318c5fb341aa9114b8268" +} diff --git a/backend/.sqlx/query-c61977907414d2336030fbab114ea03e4a1d1edb4470812cd7dd57c657fa287a.json b/backend/.sqlx/query-138fda3e2e7f83f5f60b7990efed2cedbaec80b4a54e4396b40ee5f3d15abcd2.json similarity index 63% rename from backend/.sqlx/query-c61977907414d2336030fbab114ea03e4a1d1edb4470812cd7dd57c657fa287a.json rename to backend/.sqlx/query-138fda3e2e7f83f5f60b7990efed2cedbaec80b4a54e4396b40ee5f3d15abcd2.json index 61c60afdc4..bb11e080ff 100644 --- a/backend/.sqlx/query-c61977907414d2336030fbab114ea03e4a1d1edb4470812cd7dd57c657fa287a.json +++ b/backend/.sqlx/query-138fda3e2e7f83f5f60b7990efed2cedbaec80b4a54e4396b40ee5f3d15abcd2.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO app (workspace_id, path, summary, policy, versions, extra_perms, custom_path)\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n RETURNING id", + "query": "INSERT INTO app (workspace_id, path, summary, policy, versions, extra_perms, custom_path, labels)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\n RETURNING id", "describe": { "columns": [ { @@ -17,12 +17,13 @@ "Jsonb", "Int8Array", "Jsonb", - "Text" + "Text", + "TextArray" ] }, "nullable": [ false ] }, - "hash": "c61977907414d2336030fbab114ea03e4a1d1edb4470812cd7dd57c657fa287a" + "hash": "138fda3e2e7f83f5f60b7990efed2cedbaec80b4a54e4396b40ee5f3d15abcd2" } diff --git a/backend/.sqlx/query-819c233915383e89af1bcf1a56c5f67c4e1fc217f216f609e36a9944a7807b33.json b/backend/.sqlx/query-1473ebd933fbda4550c63c81bddc3486fac4f9c2d0643e8eb15b169c1a900a3a.json similarity index 59% rename from backend/.sqlx/query-819c233915383e89af1bcf1a56c5f67c4e1fc217f216f609e36a9944a7807b33.json rename to backend/.sqlx/query-1473ebd933fbda4550c63c81bddc3486fac4f9c2d0643e8eb15b169c1a900a3a.json index 8720b09d70..993126f8ed 100644 --- a/backend/.sqlx/query-819c233915383e89af1bcf1a56c5f67c4e1fc217f216f609e36a9944a7807b33.json +++ b/backend/.sqlx/query-1473ebd933fbda4550c63c81bddc3486fac4f9c2d0643e8eb15b169c1a900a3a.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT value, description, resource_type\n FROM resource\n WHERE workspace_id = $1 AND path = $2", + "query": "SELECT value, description, resource_type, labels\n FROM resource\n WHERE workspace_id = $1 AND path = $2", "describe": { "columns": [ { @@ -17,6 +17,11 @@ "ordinal": 2, "name": "resource_type", "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "labels", + "type_info": "TextArray" } ], "parameters": { @@ -28,8 +33,9 @@ "nullable": [ true, true, - false + false, + true ] }, - "hash": "819c233915383e89af1bcf1a56c5f67c4e1fc217f216f609e36a9944a7807b33" + "hash": "1473ebd933fbda4550c63c81bddc3486fac4f9c2d0643e8eb15b169c1a900a3a" } diff --git a/backend/.sqlx/query-14bc6e1320127fe40be6f057785a88e50ab1c8c355502d7dbbe52b0e66899897.json b/backend/.sqlx/query-14bc6e1320127fe40be6f057785a88e50ab1c8c355502d7dbbe52b0e66899897.json new file mode 100644 index 0000000000..7f76bbcd16 --- /dev/null +++ b/backend/.sqlx/query-14bc6e1320127fe40be6f057785a88e50ab1c8c355502d7dbbe52b0e66899897.json @@ -0,0 +1,24 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT ($2 AND EXISTS(SELECT 1 FROM usr WHERE email = $1 AND is_admin))\n OR ($3 AND COALESCE((SELECT super_admin FROM password WHERE email = $1), false))", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "?column?", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Bool", + "Bool" + ] + }, + "nullable": [ + null + ] + }, + "hash": "14bc6e1320127fe40be6f057785a88e50ab1c8c355502d7dbbe52b0e66899897" +} diff --git a/backend/.sqlx/query-16003c729b74440f86fe511461f6c091cf865d1a6e877fe69104d59db0e13c61.json b/backend/.sqlx/query-16003c729b74440f86fe511461f6c091cf865d1a6e877fe69104d59db0e13c61.json new file mode 100644 index 0000000000..d8778a638c --- /dev/null +++ b/backend/.sqlx/query-16003c729b74440f86fe511461f6c091cf865d1a6e877fe69104d59db0e13c61.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO notify_event (channel, payload) VALUES ('notify_token_invalidation', $1)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "16003c729b74440f86fe511461f6c091cf865d1a6e877fe69104d59db0e13c61" +} diff --git a/backend/.sqlx/query-1816ab8f23338f3e01d01bf4e1ba67e1c180bd4c81b17db1ae2619e2e73fef28.json b/backend/.sqlx/query-1816ab8f23338f3e01d01bf4e1ba67e1c180bd4c81b17db1ae2619e2e73fef28.json new file mode 100644 index 0000000000..9adf12321d --- /dev/null +++ b/backend/.sqlx/query-1816ab8f23338f3e01d01bf4e1ba67e1c180bd4c81b17db1ae2619e2e73fef28.json @@ -0,0 +1,34 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT u.username, u.email,\n COALESCE(array_agg(g.group_) FILTER (WHERE g.group_ IS NOT NULL), '{}') AS \"groups!\"\n FROM usr u\n JOIN password p ON p.email = u.email AND p.login_type = 'password'\n LEFT JOIN usr_to_group g ON g.workspace_id = u.workspace_id AND g.usr = u.username\n WHERE u.workspace_id = $1 AND NOT u.is_service_account\n GROUP BY u.username, u.email\n ORDER BY u.username", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "username", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "groups!", + "type_info": "VarcharArray" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + false, + null + ] + }, + "hash": "1816ab8f23338f3e01d01bf4e1ba67e1c180bd4c81b17db1ae2619e2e73fef28" +} diff --git a/backend/.sqlx/query-22b6a5e8d05d47c86713ff804857e037112aac008865934fa3419581034e69d3.json b/backend/.sqlx/query-22b6a5e8d05d47c86713ff804857e037112aac008865934fa3419581034e69d3.json new file mode 100644 index 0000000000..5baa9381b4 --- /dev/null +++ b/backend/.sqlx/query-22b6a5e8d05d47c86713ff804857e037112aac008865934fa3419581034e69d3.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT login_type, username FROM password WHERE email = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "login_type", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "username", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + true + ] + }, + "hash": "22b6a5e8d05d47c86713ff804857e037112aac008865934fa3419581034e69d3" +} diff --git a/backend/.sqlx/query-235d480efa2a0d8ea0a530454a52aa1fa5a76623cf2e7b75774435cdac9720d0.json b/backend/.sqlx/query-235d480efa2a0d8ea0a530454a52aa1fa5a76623cf2e7b75774435cdac9720d0.json new file mode 100644 index 0000000000..92fffa33a5 --- /dev/null +++ b/backend/.sqlx/query-235d480efa2a0d8ea0a530454a52aa1fa5a76623cf2e7b75774435cdac9720d0.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT super_admin, login_type = 'password' AND totp_secret IS NULL AS \"lacks_totp!\"\n FROM password WHERE email = $1 AND disabled = false", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "super_admin", + "type_info": "Bool" + }, + { + "ordinal": 1, + "name": "lacks_totp!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + null + ] + }, + "hash": "235d480efa2a0d8ea0a530454a52aa1fa5a76623cf2e7b75774435cdac9720d0" +} diff --git a/backend/.sqlx/query-25a603879c2324cf4390a4d8ff3ce820f1f96d2c22e645a17b1125a949f8dd88.json b/backend/.sqlx/query-25a603879c2324cf4390a4d8ff3ce820f1f96d2c22e645a17b1125a949f8dd88.json new file mode 100644 index 0000000000..706a5eb2c5 --- /dev/null +++ b/backend/.sqlx/query-25a603879c2324cf4390a4d8ff3ce820f1f96d2c22e645a17b1125a949f8dd88.json @@ -0,0 +1,97 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT j.id AS \"id!\",\n COALESCE(j.root_job, j.parent_job, j.id) AS \"root_job_id!\",\n j.runnable_path,\n j.permissioned_as_email AS \"email!\",\n j.created_by AS \"created_by!\",\n j.created_at AS \"created_at!\",\n COALESCE(rj.runnable_path, j.runnable_path) AS flow_path,\n NULLIF(f.summary, '') AS flow_summary,\n s.flow_status->'approval_conditions' AS approval_conditions,\n NULLIF(w.m->'home'->>'step_summary', '') AS step_summary,\n COALESCE((w.m->>'count')::bigint, 1) AS \"required_approvals!\",\n -- Counted as the worker counts them: those sent to the approval step's job,\n -- plus those sent to the flow itself.\n (SELECT count(*) FROM resume_job r WHERE r.job IN (j.id, (w.m->>'job')::uuid))\n AS \"approvals!\",\n EXISTS(SELECT 1 FROM resume_job r\n WHERE r.job IN (j.id, (w.m->>'job')::uuid) AND r.approver = $2)\n AS \"approved_by_me!\"\n FROM v2_job_queue q\n JOIN v2_job j ON j.id = q.id\n JOIN v2_job_status s ON s.id = q.id\n LEFT JOIN v2_job rj ON rj.id = COALESCE(j.root_job, j.parent_job)\n LEFT JOIN flow f\n ON f.workspace_id = j.workspace_id\n AND f.path = COALESCE(rj.runnable_path, j.runnable_path)\n -- The step waiting on the approval, which the worker marks `home` when the approval\n -- step has `show_on_home`: only those are listed, since many approvals are announced\n -- elsewhere (a resume link sent to a chat) and every admin and owner could give them.\n CROSS JOIN LATERAL (\n SELECT s.flow_status->'modules'->((s.flow_status->>'step')::int) AS m\n ) w\n WHERE q.workspace_id = $1\n AND q.suspend > 0\n AND w.m->>'type' = 'WaitingForEvents'\n AND w.m->'home' IS NOT NULL\n AND ($4::text[] IS NULL OR j.tag = ANY($4))\n ORDER BY j.created_at DESC\n LIMIT $3\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id!", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "root_job_id!", + "type_info": "Uuid" + }, + { + "ordinal": 2, + "name": "runnable_path", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "email!", + "type_info": "Varchar" + }, + { + "ordinal": 4, + "name": "created_by!", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "created_at!", + "type_info": "Timestamptz" + }, + { + "ordinal": 6, + "name": "flow_path", + "type_info": "Varchar" + }, + { + "ordinal": 7, + "name": "flow_summary", + "type_info": "Text" + }, + { + "ordinal": 8, + "name": "approval_conditions", + "type_info": "Jsonb" + }, + { + "ordinal": 9, + "name": "step_summary", + "type_info": "Text" + }, + { + "ordinal": 10, + "name": "required_approvals!", + "type_info": "Int8" + }, + { + "ordinal": 11, + "name": "approvals!", + "type_info": "Int8" + }, + { + "ordinal": 12, + "name": "approved_by_me!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Int8", + "TextArray" + ] + }, + "nullable": [ + false, + null, + true, + false, + false, + false, + null, + null, + null, + null, + null, + null, + null + ] + }, + "hash": "25a603879c2324cf4390a4d8ff3ce820f1f96d2c22e645a17b1125a949f8dd88" +} diff --git a/backend/.sqlx/query-25ddcc281bb8a5f046176bc57749f3e17e9346c3822336c7b001e04a711449a8.json b/backend/.sqlx/query-25ddcc281bb8a5f046176bc57749f3e17e9346c3822336c7b001e04a711449a8.json new file mode 100644 index 0000000000..a553447405 --- /dev/null +++ b/backend/.sqlx/query-25ddcc281bb8a5f046176bc57749f3e17e9346c3822336c7b001e04a711449a8.json @@ -0,0 +1,44 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT to_char(timestamp AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS \"day!\",\n id AS \"id!\",\n timestamp AS \"ts!\",\n row_to_json(r)::text AS \"line!\"\n FROM (\n SELECT workspace_id, id, timestamp, username, operation,\n action_kind::text AS action_kind, resource, parameters, email, span,\n client_ip, user_agent, peer_ip, forwarded_for\n FROM audit_partitioned\n WHERE timestamp >= $1 AND timestamp < $2\n AND (timestamp, id) > ($3, $4)\n ORDER BY timestamp, id\n LIMIT $5\n ) r\n ORDER BY timestamp, id", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "day!", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "id!", + "type_info": "Int8" + }, + { + "ordinal": 2, + "name": "ts!", + "type_info": "Timestamptz" + }, + { + "ordinal": 3, + "name": "line!", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Timestamptz", + "Timestamptz", + "Timestamptz", + "Int8", + "Int8" + ] + }, + "nullable": [ + null, + false, + false, + null + ] + }, + "hash": "25ddcc281bb8a5f046176bc57749f3e17e9346c3822336c7b001e04a711449a8" +} diff --git a/backend/.sqlx/query-269ef755d901662606ce1a4dbcf333331b8500e25ee4196bd5261a953ef876da.json b/backend/.sqlx/query-269ef755d901662606ce1a4dbcf333331b8500e25ee4196bd5261a953ef876da.json new file mode 100644 index 0000000000..add1d846f3 --- /dev/null +++ b/backend/.sqlx/query-269ef755d901662606ce1a4dbcf333331b8500e25ee4196bd5261a953ef876da.json @@ -0,0 +1,24 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT path FROM resource\n WHERE workspace_id = $1 AND path = ANY($2) AND extra_perms ?| $3", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "path", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "TextArray", + "TextArray" + ] + }, + "nullable": [ + false + ] + }, + "hash": "269ef755d901662606ce1a4dbcf333331b8500e25ee4196bd5261a953ef876da" +} diff --git a/backend/.sqlx/query-2aaac7db9463db32f8fb24418aad9aa1e775741631cef8da46d922a0ac63d9b3.json b/backend/.sqlx/query-2aaac7db9463db32f8fb24418aad9aa1e775741631cef8da46d922a0ac63d9b3.json deleted file mode 100644 index 4524f105bc..0000000000 --- a/backend/.sqlx/query-2aaac7db9463db32f8fb24418aad9aa1e775741631cef8da46d922a0ac63d9b3.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE token SET super_admin = $1 WHERE email = $2 AND label != 'session'\n AND (NOT $1 OR NOT EXISTS (SELECT 1 FROM unnest(scopes) s WHERE s LIKE 'mcp:%'))", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Bool", - "Text" - ] - }, - "nullable": [] - }, - "hash": "2aaac7db9463db32f8fb24418aad9aa1e775741631cef8da46d922a0ac63d9b3" -} diff --git a/backend/.sqlx/query-fd4c5391107af34a3bf9b83b0c3f7d5ee9490240a627b20a1037444845e39c5f.json b/backend/.sqlx/query-2c70b10578338d5722e5fa4f43b92ab3384f62ae44824b3ba15a4d7921435ca7.json similarity index 64% rename from backend/.sqlx/query-fd4c5391107af34a3bf9b83b0c3f7d5ee9490240a627b20a1037444845e39c5f.json rename to backend/.sqlx/query-2c70b10578338d5722e5fa4f43b92ab3384f62ae44824b3ba15a4d7921435ca7.json index 50cf586c79..0704b15557 100644 --- a/backend/.sqlx/query-fd4c5391107af34a3bf9b83b0c3f7d5ee9490240a627b20a1037444845e39c5f.json +++ b/backend/.sqlx/query-2c70b10578338d5722e5fa4f43b92ab3384f62ae44824b3ba15a4d7921435ca7.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO token\n (token_hash, token_prefix, token, label, super_admin, email)\n VALUES ($1, $2, $3, $4, $5, $6)", + "query": "INSERT INTO token\n (token_hash, token_prefix, token, label, super_admin, email, admin)\n VALUES ($1, $2, $3, $4, $5, $6, true)", "describe": { "columns": [], "parameters": { @@ -15,5 +15,5 @@ }, "nullable": [] }, - "hash": "fd4c5391107af34a3bf9b83b0c3f7d5ee9490240a627b20a1037444845e39c5f" + "hash": "2c70b10578338d5722e5fa4f43b92ab3384f62ae44824b3ba15a4d7921435ca7" } diff --git a/backend/.sqlx/query-305f8db93baaa55c2b46192eea353f84ba03bf0c9a8a409386c6c1ef5305dc8d.json b/backend/.sqlx/query-305f8db93baaa55c2b46192eea353f84ba03bf0c9a8a409386c6c1ef5305dc8d.json new file mode 100644 index 0000000000..1068c0b10f --- /dev/null +++ b/backend/.sqlx/query-305f8db93baaa55c2b46192eea353f84ba03bf0c9a8a409386c6c1ef5305dc8d.json @@ -0,0 +1,21 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO token\n (token_hash, token_prefix, token, email, label, expiration, super_admin, owner, allowed_ips, admin)\n VALUES ($1, $2, $3, $4, $5, $6, false, $7, $8::text[]::cidr[], true)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Timestamptz", + "Varchar", + "TextArray" + ] + }, + "nullable": [] + }, + "hash": "305f8db93baaa55c2b46192eea353f84ba03bf0c9a8a409386c6c1ef5305dc8d" +} diff --git a/backend/.sqlx/query-31c9a45b4db0ceca15338aa9e95a4a4eb82c330c9838c8358d1067e6a6dc05dd.json b/backend/.sqlx/query-31c9a45b4db0ceca15338aa9e95a4a4eb82c330c9838c8358d1067e6a6dc05dd.json new file mode 100644 index 0000000000..16077a65f4 --- /dev/null +++ b/backend/.sqlx/query-31c9a45b4db0ceca15338aa9e95a4a4eb82c330c9838c8358d1067e6a6dc05dd.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT email FROM password WHERE totp_secret IS NOT NULL", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "email", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false + ] + }, + "hash": "31c9a45b4db0ceca15338aa9e95a4a4eb82c330c9838c8358d1067e6a6dc05dd" +} diff --git a/backend/.sqlx/query-19c481a0d6ecd4c0dfab6973e4732c2146953253ba6062ab05b34b6b35e41f66.json b/backend/.sqlx/query-3339c1d01792ff181f9506b57c7e6771c3a1a2a5a67dd467ed263b3501c5d279.json similarity index 78% rename from backend/.sqlx/query-19c481a0d6ecd4c0dfab6973e4732c2146953253ba6062ab05b34b6b35e41f66.json rename to backend/.sqlx/query-3339c1d01792ff181f9506b57c7e6771c3a1a2a5a67dd467ed263b3501c5d279.json index 4521496742..5f6c31d752 100644 --- a/backend/.sqlx/query-19c481a0d6ecd4c0dfab6973e4732c2146953253ba6062ab05b34b6b35e41f66.json +++ b/backend/.sqlx/query-3339c1d01792ff181f9506b57c7e6771c3a1a2a5a67dd467ed263b3501c5d279.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE volume\n SET size_bytes = $3, file_count = $4,\n updated_at = now(), updated_by = $5, last_used_at = now(),\n lease_until = NULL, leased_by = NULL, generation = generation + generation % 2\n WHERE workspace_id = $1 AND name = $2", + "query": "UPDATE volume\n SET size_bytes = $3, file_count = $4,\n updated_at = now(), updated_by = $5, last_used_at = now(),\n lease_until = NULL, leased_by = NULL, generation = generation + generation % 2\n WHERE workspace_id = $1 AND name = $2 AND leased_by = $5", "describe": { "columns": [], "parameters": { @@ -14,5 +14,5 @@ }, "nullable": [] }, - "hash": "19c481a0d6ecd4c0dfab6973e4732c2146953253ba6062ab05b34b6b35e41f66" + "hash": "3339c1d01792ff181f9506b57c7e6771c3a1a2a5a67dd467ed263b3501c5d279" } diff --git a/backend/.sqlx/query-34854f8d651562512ac522db1dc0c43946b7440bd427d045b8d8b83ba7a3ab26.json b/backend/.sqlx/query-34854f8d651562512ac522db1dc0c43946b7440bd427d045b8d8b83ba7a3ab26.json new file mode 100644 index 0000000000..3e3d3cce46 --- /dev/null +++ b/backend/.sqlx/query-34854f8d651562512ac522db1dc0c43946b7440bd427d045b8d8b83ba7a3ab26.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT r AS risk, count(*) AS n FROM token_risk, unnest(risks) r WHERE email = $1 GROUP BY r", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "risk", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "n", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null, + null + ] + }, + "hash": "34854f8d651562512ac522db1dc0c43946b7440bd427d045b8d8b83ba7a3ab26" +} diff --git a/backend/.sqlx/query-36270d5bc57411ee110b5299ceb04e0c39747ff8f2aebfed1e3478c4baa2b748.json b/backend/.sqlx/query-36270d5bc57411ee110b5299ceb04e0c39747ff8f2aebfed1e3478c4baa2b748.json new file mode 100644 index 0000000000..6356c66a3e --- /dev/null +++ b/backend/.sqlx/query-36270d5bc57411ee110b5299ceb04e0c39747ff8f2aebfed1e3478c4baa2b748.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE v2_job_queue\n SET canceled_by = $3, canceled_reason = $4, scheduled_for = now(), suspend = 0\n WHERE id = ANY($2) AND workspace_id = $5 AND canceled_by IS NULL\n AND (suspend > 0 OR NOT running)\n AND NOT EXISTS (SELECT 1 FROM v2_job c WHERE c.parent_job = v2_job_queue.id)\n AND (SELECT count(*) FROM v2_job_status s,\n jsonb_array_elements(s.flow_status->'modules'->$6::int->'flow_jobs_success') e\n WHERE s.id = $1 AND e = 'false'::jsonb) >= $7", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "UuidArray", + "Varchar", + "Text", + "Text", + "Int4", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "36270d5bc57411ee110b5299ceb04e0c39747ff8f2aebfed1e3478c4baa2b748" +} diff --git a/backend/.sqlx/query-a6fe41e36e06c88e1387abaea17107ceab2c5b17258958bde03b3e492bb2790e.json b/backend/.sqlx/query-398b309a86c3abe0b8daf2ec256dd4eac403ea69d09d7b13d6f5a0b21e2b034a.json similarity index 73% rename from backend/.sqlx/query-a6fe41e36e06c88e1387abaea17107ceab2c5b17258958bde03b3e492bb2790e.json rename to backend/.sqlx/query-398b309a86c3abe0b8daf2ec256dd4eac403ea69d09d7b13d6f5a0b21e2b034a.json index 7c2918993b..533862e344 100644 --- a/backend/.sqlx/query-a6fe41e36e06c88e1387abaea17107ceab2c5b17258958bde03b3e492bb2790e.json +++ b/backend/.sqlx/query-398b309a86c3abe0b8daf2ec256dd4eac403ea69d09d7b13d6f5a0b21e2b034a.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT hash, created_at, content, summary, description, lock, schema\n FROM script\n WHERE workspace_id = $1 AND path = $2 AND archived = false\n ORDER BY created_at DESC\n LIMIT 1", + "query": "SELECT hash, created_at, content, summary, description, lock, schema, labels\n FROM script\n WHERE workspace_id = $1 AND path = $2 AND archived = false\n ORDER BY created_at DESC\n LIMIT 1", "describe": { "columns": [ { @@ -37,6 +37,11 @@ "ordinal": 6, "name": "schema", "type_info": "Json" + }, + { + "ordinal": 7, + "name": "labels", + "type_info": "TextArray" } ], "parameters": { @@ -52,8 +57,9 @@ false, false, true, + true, true ] }, - "hash": "a6fe41e36e06c88e1387abaea17107ceab2c5b17258958bde03b3e492bb2790e" + "hash": "398b309a86c3abe0b8daf2ec256dd4eac403ea69d09d7b13d6f5a0b21e2b034a" } diff --git a/backend/.sqlx/query-3c2031a385e80273a15d45d45ede51c89c6fdadfcce19f23c518040e82d1df69.json b/backend/.sqlx/query-3c2031a385e80273a15d45d45ede51c89c6fdadfcce19f23c518040e82d1df69.json new file mode 100644 index 0000000000..0ad1d8a7c3 --- /dev/null +++ b/backend/.sqlx/query-3c2031a385e80273a15d45d45ede51c89c6fdadfcce19f23c518040e82d1df69.json @@ -0,0 +1,65 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE token SET last_used_at = now() WHERE\n token_hash = $1\n AND (expiration > NOW() OR expiration IS NULL)\n AND (workspace_id IS NULL OR workspace_id = $2)\n RETURNING owner, email, super_admin, scopes, label, read_only,\n allowed_ips::text[] AS allowed_ips, admin", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "owner", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "super_admin", + "type_info": "Bool" + }, + { + "ordinal": 3, + "name": "scopes", + "type_info": "TextArray" + }, + { + "ordinal": 4, + "name": "label", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "read_only", + "type_info": "Bool" + }, + { + "ordinal": 6, + "name": "allowed_ips", + "type_info": "TextArray" + }, + { + "ordinal": 7, + "name": "admin", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + true, + true, + false, + true, + true, + false, + null, + false + ] + }, + "hash": "3c2031a385e80273a15d45d45ede51c89c6fdadfcce19f23c518040e82d1df69" +} diff --git a/backend/.sqlx/query-456f07b39a39791ea4c0764adc235374571db2fa45b6e97db42e8309ecb02c05.json b/backend/.sqlx/query-456f07b39a39791ea4c0764adc235374571db2fa45b6e97db42e8309ecb02c05.json new file mode 100644 index 0000000000..051fcda620 --- /dev/null +++ b/backend/.sqlx/query-456f07b39a39791ea4c0764adc235374571db2fa45b6e97db42e8309ecb02c05.json @@ -0,0 +1,41 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT resume_id, approver, created_at, approved FROM resume_job\n WHERE flow = $1 AND ($2::uuid IS NULL OR job IN ($1, $2))", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "resume_id", + "type_info": "Int4" + }, + { + "ordinal": 1, + "name": "approver", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "created_at", + "type_info": "Timestamptz" + }, + { + "ordinal": 3, + "name": "approved", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [ + false, + true, + false, + false + ] + }, + "hash": "456f07b39a39791ea4c0764adc235374571db2fa45b6e97db42e8309ecb02c05" +} diff --git a/backend/.sqlx/query-483d07c7ad9cf0cb402a5800445cd3f22d75213ebb950af902c4a3fc078f5017.json b/backend/.sqlx/query-483d07c7ad9cf0cb402a5800445cd3f22d75213ebb950af902c4a3fc078f5017.json new file mode 100644 index 0000000000..c989528a7a --- /dev/null +++ b/backend/.sqlx/query-483d07c7ad9cf0cb402a5800445cd3f22d75213ebb950af902c4a3fc078f5017.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT account FROM variable WHERE workspace_id = 'test-workspace' AND path = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "account", + "type_info": "Int4" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + true + ] + }, + "hash": "483d07c7ad9cf0cb402a5800445cd3f22d75213ebb950af902c4a3fc078f5017" +} diff --git a/backend/.sqlx/query-4a5679413cd1f5b1b2822a4804a54b2a5a008d7c3313c90fb80d431057223b34.json b/backend/.sqlx/query-4a5679413cd1f5b1b2822a4804a54b2a5a008d7c3313c90fb80d431057223b34.json new file mode 100644 index 0000000000..0c7daafc42 --- /dev/null +++ b/backend/.sqlx/query-4a5679413cd1f5b1b2822a4804a54b2a5a008d7c3313c90fb80d431057223b34.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO flow (\n workspace_id, path, summary, description, value, edited_by, edited_at,\n archived, schema, extra_perms, dependency_job, tag,\n ws_error_handler_muted, dedicated_worker, timeout, visible_to_runner_only,\n concurrency_key, versions, on_behalf_of, on_behalf_of_email, lock_error_logs,\n job_token_scopes, labels\n )\n SELECT $2, path, summary, description, value, edited_by, edited_at,\n archived, schema, extra_perms, NULL, tag,\n ws_error_handler_muted, dedicated_worker, timeout, visible_to_runner_only,\n concurrency_key, ARRAY[]::bigint[],\n -- Same predicate as clone_scripts.\n CASE WHEN on_behalf_of LIKE 'u/%' THEN\n (SELECT on_behalf_of WHERE EXISTS (\n SELECT 1 FROM usr u WHERE u.workspace_id = $2::varchar\n AND u.username = substring(on_behalf_of from 3)\n UNION ALL\n SELECT 1 FROM password p WHERE p.super_admin\n AND (p.username = substring(on_behalf_of from 3)\n OR p.email = substring(on_behalf_of from 3))))\n WHEN on_behalf_of LIKE 'g/%' THEN\n (SELECT on_behalf_of WHERE EXISTS (\n SELECT 1 FROM group_ g WHERE g.workspace_id = $2::varchar\n AND g.name = substring(on_behalf_of from 3)))\n ELSE\n (SELECT on_behalf_of WHERE EXISTS (\n SELECT 1 FROM usr u WHERE u.workspace_id = $2::varchar\n AND u.username = on_behalf_of\n UNION ALL\n SELECT 1 FROM password p WHERE p.email = on_behalf_of\n AND p.super_admin))\n END, on_behalf_of_email, lock_error_logs, job_token_scopes, labels\n FROM flow\n WHERE workspace_id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "4a5679413cd1f5b1b2822a4804a54b2a5a008d7c3313c90fb80d431057223b34" +} diff --git a/backend/.sqlx/query-4b8fe0471867cbf4bbb571eae4fc097b36b70a46748fa0c2eedae610173bde86.json b/backend/.sqlx/query-4b8fe0471867cbf4bbb571eae4fc097b36b70a46748fa0c2eedae610173bde86.json new file mode 100644 index 0000000000..c5797b6bfb --- /dev/null +++ b/backend/.sqlx/query-4b8fe0471867cbf4bbb571eae4fc097b36b70a46748fa0c2eedae610173bde86.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT 1 AS \"one!\" FROM workspace_key\n WHERE workspace_id = 'admins' AND kind = 'cloud' FOR UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "one!", + "type_info": "Int4" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + null + ] + }, + "hash": "4b8fe0471867cbf4bbb571eae4fc097b36b70a46748fa0c2eedae610173bde86" +} diff --git a/backend/.sqlx/query-4c100853478519e794d05fe6070acfe8ddb246ceaed99e9e25f6bd34b105c6de.json b/backend/.sqlx/query-4c100853478519e794d05fe6070acfe8ddb246ceaed99e9e25f6bd34b105c6de.json new file mode 100644 index 0000000000..121eadc9b0 --- /dev/null +++ b/backend/.sqlx/query-4c100853478519e794d05fe6070acfe8ddb246ceaed99e9e25f6bd34b105c6de.json @@ -0,0 +1,38 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM password RETURNING email, totp_secret, totp_last_step, totp_recovery_codes", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "totp_secret", + "type_info": "Text" + }, + { + "ordinal": 2, + "name": "totp_last_step", + "type_info": "Int8" + }, + { + "ordinal": 3, + "name": "totp_recovery_codes", + "type_info": "TextArray" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false, + true, + true, + true + ] + }, + "hash": "4c100853478519e794d05fe6070acfe8ddb246ceaed99e9e25f6bd34b105c6de" +} diff --git a/backend/.sqlx/query-4d6646a2bccd6599cdd0d603a2e64f621449524162ef02ff52825af519f576e9.json b/backend/.sqlx/query-4d6646a2bccd6599cdd0d603a2e64f621449524162ef02ff52825af519f576e9.json new file mode 100644 index 0000000000..8bf052ee38 --- /dev/null +++ b/backend/.sqlx/query-4d6646a2bccd6599cdd0d603a2e64f621449524162ef02ff52825af519f576e9.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT password_hash FROM password WHERE email = $1 AND login_type = 'password'", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "password_hash", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + true + ] + }, + "hash": "4d6646a2bccd6599cdd0d603a2e64f621449524162ef02ff52825af519f576e9" +} diff --git a/backend/.sqlx/query-4e57eb6c62eb8a04088e91cae5cf955af22d885b24908c3beb949be24378797f.json b/backend/.sqlx/query-4e57eb6c62eb8a04088e91cae5cf955af22d885b24908c3beb949be24378797f.json new file mode 100644 index 0000000000..560d5b017f --- /dev/null +++ b/backend/.sqlx/query-4e57eb6c62eb8a04088e91cae5cf955af22d885b24908c3beb949be24378797f.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE password SET\n totp_failed_attempts = CASE WHEN totp_failed_since > now() - interval '1 minute'\n THEN totp_failed_attempts + 1 ELSE 1 END,\n totp_failed_since = CASE WHEN totp_failed_since > now() - interval '1 minute'\n THEN totp_failed_since ELSE now() END\n WHERE email = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "4e57eb6c62eb8a04088e91cae5cf955af22d885b24908c3beb949be24378797f" +} diff --git a/backend/.sqlx/query-26fb727ef7d50c93c1c8ce33356ef6feafc448e70c30ba7e7c835f5e3167f3a5.json b/backend/.sqlx/query-4fff0ec1067f69aa3b67f73e3a7c84177a1050456baa43d348e8b467c5db3b75.json similarity index 79% rename from backend/.sqlx/query-26fb727ef7d50c93c1c8ce33356ef6feafc448e70c30ba7e7c835f5e3167f3a5.json rename to backend/.sqlx/query-4fff0ec1067f69aa3b67f73e3a7c84177a1050456baa43d348e8b467c5db3b75.json index 2d22e40cc7..3e55b738b2 100644 --- a/backend/.sqlx/query-26fb727ef7d50c93c1c8ce33356ef6feafc448e70c30ba7e7c835f5e3167f3a5.json +++ b/backend/.sqlx/query-4fff0ec1067f69aa3b67f73e3a7c84177a1050456baa43d348e8b467c5db3b75.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id, workspace_id, path, summary, policy, versions, extra_perms, custom_path\n FROM app\n WHERE workspace_id = $1", + "query": "SELECT id, workspace_id, path, summary, policy, versions, extra_perms, custom_path, labels\n FROM app\n WHERE workspace_id = $1", "describe": { "columns": [ { @@ -42,6 +42,11 @@ "ordinal": 7, "name": "custom_path", "type_info": "Text" + }, + { + "ordinal": 8, + "name": "labels", + "type_info": "TextArray" } ], "parameters": { @@ -57,8 +62,9 @@ false, false, false, + true, true ] }, - "hash": "26fb727ef7d50c93c1c8ce33356ef6feafc448e70c30ba7e7c835f5e3167f3a5" + "hash": "4fff0ec1067f69aa3b67f73e3a7c84177a1050456baa43d348e8b467c5db3b75" } diff --git a/backend/.sqlx/query-536bda805dc3d1a5e66185787749b02dbefe608a83564cf165157230a4887639.json b/backend/.sqlx/query-536bda805dc3d1a5e66185787749b02dbefe608a83564cf165157230a4887639.json new file mode 100644 index 0000000000..8abcf226be --- /dev/null +++ b/backend/.sqlx/query-536bda805dc3d1a5e66185787749b02dbefe608a83564cf165157230a4887639.json @@ -0,0 +1,32 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT email, totp_secret, totp_pending_secret FROM password\n WHERE totp_secret IS NOT NULL OR totp_pending_secret IS NOT NULL FOR UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "totp_secret", + "type_info": "Text" + }, + { + "ordinal": 2, + "name": "totp_pending_secret", + "type_info": "Text" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false, + true, + true + ] + }, + "hash": "536bda805dc3d1a5e66185787749b02dbefe608a83564cf165157230a4887639" +} diff --git a/backend/.sqlx/query-547f245179c2f91275a0b8e00e5dc327f3a6fe55fb9020c922603e4e7946b49c.json b/backend/.sqlx/query-547f245179c2f91275a0b8e00e5dc327f3a6fe55fb9020c922603e4e7946b49c.json new file mode 100644 index 0000000000..adebd908b1 --- /dev/null +++ b/backend/.sqlx/query-547f245179c2f91275a0b8e00e5dc327f3a6fe55fb9020c922603e4e7946b49c.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE password SET totp_secret = NULL, totp_pending_secret = NULL, totp_last_step = NULL,\n totp_recovery_codes = NULL, totp_failed_attempts = 0, totp_failed_since = NULL\n WHERE email = $1 AND (totp_secret IS NOT NULL OR totp_pending_secret IS NOT NULL)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "547f245179c2f91275a0b8e00e5dc327f3a6fe55fb9020c922603e4e7946b49c" +} diff --git a/backend/.sqlx/query-562275b5ac29438796d01d8cfb885f4b31f6b4834687e0c06d1274b5c84b3a0d.json b/backend/.sqlx/query-562275b5ac29438796d01d8cfb885f4b31f6b4834687e0c06d1274b5c84b3a0d.json new file mode 100644 index 0000000000..153b3e00b8 --- /dev/null +++ b/backend/.sqlx/query-562275b5ac29438796d01d8cfb885f4b31f6b4834687e0c06d1274b5c84b3a0d.json @@ -0,0 +1,25 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin, scopes, workspace_id, owner, expiration, allowed_ips, admin)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::text[]::cidr[], $12)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Bool", + "TextArray", + "Varchar", + "Varchar", + "Timestamptz", + "TextArray", + "Bool" + ] + }, + "nullable": [] + }, + "hash": "562275b5ac29438796d01d8cfb885f4b31f6b4834687e0c06d1274b5c84b3a0d" +} diff --git a/backend/.sqlx/query-58bb4c7646404beae1f2183b13aef01f3c1737a1ff5f86c37211ff4aa3290b66.json b/backend/.sqlx/query-58bb4c7646404beae1f2183b13aef01f3c1737a1ff5f86c37211ff4aa3290b66.json new file mode 100644 index 0000000000..2c01dc53c0 --- /dev/null +++ b/backend/.sqlx/query-58bb4c7646404beae1f2183b13aef01f3c1737a1ff5f86c37211ff4aa3290b66.json @@ -0,0 +1,26 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT r AS risk, count(*) AS n FROM token_risk, unnest(risks) r GROUP BY r", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "risk", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "n", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + null, + null + ] + }, + "hash": "58bb4c7646404beae1f2183b13aef01f3c1737a1ff5f86c37211ff4aa3290b66" +} diff --git a/backend/.sqlx/query-8039b459914ceefe0c0a31b97473a5522e47b4b2fd3ddeff8f221560bc9c6f57.json b/backend/.sqlx/query-5bd796933edd56a80add193599714e763d17f9514b0746e9e389699c95f6bb7d.json similarity index 65% rename from backend/.sqlx/query-8039b459914ceefe0c0a31b97473a5522e47b4b2fd3ddeff8f221560bc9c6f57.json rename to backend/.sqlx/query-5bd796933edd56a80add193599714e763d17f9514b0746e9e389699c95f6bb7d.json index 9210bb8a8b..082c1c9d7f 100644 --- a/backend/.sqlx/query-8039b459914ceefe0c0a31b97473a5522e47b4b2fd3ddeff8f221560bc9c6f57.json +++ b/backend/.sqlx/query-5bd796933edd56a80add193599714e763d17f9514b0746e9e389699c95f6bb7d.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT display_name, owners, extra_perms, summary\n FROM folder\n WHERE workspace_id = $1 AND name = $2", + "query": "SELECT display_name, owners, extra_perms, summary, labels\n FROM folder\n WHERE workspace_id = $1 AND name = $2", "describe": { "columns": [ { @@ -22,6 +22,11 @@ "ordinal": 3, "name": "summary", "type_info": "Text" + }, + { + "ordinal": 4, + "name": "labels", + "type_info": "TextArray" } ], "parameters": { @@ -34,8 +39,9 @@ false, false, false, + true, true ] }, - "hash": "8039b459914ceefe0c0a31b97473a5522e47b4b2fd3ddeff8f221560bc9c6f57" + "hash": "5bd796933edd56a80add193599714e763d17f9514b0746e9e389699c95f6bb7d" } diff --git a/backend/.sqlx/query-6141c832d916e87dfb353ac73ae4d06088cbdbac4f1a8e7859adfed4c6f64dac.json b/backend/.sqlx/query-6141c832d916e87dfb353ac73ae4d06088cbdbac4f1a8e7859adfed4c6f64dac.json new file mode 100644 index 0000000000..7a4c09f8a8 --- /dev/null +++ b/backend/.sqlx/query-6141c832d916e87dfb353ac73ae4d06088cbdbac4f1a8e7859adfed4c6f64dac.json @@ -0,0 +1,30 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE token t SET label = $1\n FROM token old\n WHERE old.token_hash = t.token_hash\n AND t.email = $2 AND t.token_prefix = $3\n AND (t.label IS NULL OR (\n t.label <> 'session'\n AND t.label <> 'guest_session'\n AND lower(t.label) NOT LIKE 'ephemeral%'\n AND t.label <> 'debugger-token'\n AND t.label NOT LIKE 'mcp-oauth-%'\n AND NOT starts_with(t.label, 'embed_app:')\n AND NOT starts_with(t.label, 'sdk_app:')\n AND NOT starts_with(t.label, 'impersonation:')\n AND NOT starts_with(t.label, 'cli-login:')\n AND NOT starts_with(t.label, 'remote-deploy:')\n ))\n RETURNING t.token_prefix, old.label AS previous_label", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "token_prefix", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "previous_label", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Varchar", + "Text", + "Text" + ] + }, + "nullable": [ + false, + true + ] + }, + "hash": "6141c832d916e87dfb353ac73ae4d06088cbdbac4f1a8e7859adfed4c6f64dac" +} diff --git a/backend/.sqlx/query-62e8902d2e50191325524827b8ed7e8f4bf2a2b54b8522b52c47f8249ba624b0.json b/backend/.sqlx/query-62e8902d2e50191325524827b8ed7e8f4bf2a2b54b8522b52c47f8249ba624b0.json new file mode 100644 index 0000000000..9337d651e2 --- /dev/null +++ b/backend/.sqlx/query-62e8902d2e50191325524827b8ed7e8f4bf2a2b54b8522b52c47f8249ba624b0.json @@ -0,0 +1,47 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT v.path, r.created_by AS \"owner?\", false AS \"workspace!\", a.scopes AS \"scopes?\",\n NULL::text[] AS \"missing_scopes?\"\n FROM variable v\n JOIN resource r ON r.workspace_id = v.workspace_id AND r.path = v.path\n LEFT JOIN account a ON a.workspace_id = v.workspace_id AND a.id = v.account\n WHERE v.workspace_id = $1 AND r.resource_type = $2\n ORDER BY v.path", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "path", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "owner?", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "workspace!", + "type_info": "Bool" + }, + { + "ordinal": 3, + "name": "scopes?", + "type_info": "TextArray" + }, + { + "ordinal": 4, + "name": "missing_scopes?", + "type_info": "TextArray" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + true, + null, + true, + null + ] + }, + "hash": "62e8902d2e50191325524827b8ed7e8f4bf2a2b54b8522b52c47f8249ba624b0" +} diff --git a/backend/.sqlx/query-6550c0a58ae0b258d9b101683f5a14c9edc522a2895925263286fd41d13ff9c7.json b/backend/.sqlx/query-6550c0a58ae0b258d9b101683f5a14c9edc522a2895925263286fd41d13ff9c7.json new file mode 100644 index 0000000000..41442611fd --- /dev/null +++ b/backend/.sqlx/query-6550c0a58ae0b258d9b101683f5a14c9edc522a2895925263286fd41d13ff9c7.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT favorite_kind::text AS \"kind!\", path FROM favorite\n WHERE usr = $1 AND workspace_id = $2 AND favorite_kind IN ('script', 'flow')", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "kind!", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "path", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null, + false + ] + }, + "hash": "6550c0a58ae0b258d9b101683f5a14c9edc522a2895925263286fd41d13ff9c7" +} diff --git a/backend/.sqlx/query-6bbf56bbc7b647daaba8dc5a4d49bffa976b5da8e8052638b8ee3e3c834dac27.json b/backend/.sqlx/query-6bbf56bbc7b647daaba8dc5a4d49bffa976b5da8e8052638b8ee3e3c834dac27.json new file mode 100644 index 0000000000..a554161d15 --- /dev/null +++ b/backend/.sqlx/query-6bbf56bbc7b647daaba8dc5a4d49bffa976b5da8e8052638b8ee3e3c834dac27.json @@ -0,0 +1,52 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT email, workspace_id, super_admin, owner, allowed_ips::text[] AS allowed_ips, admin\n FROM token WHERE token_hash = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "super_admin", + "type_info": "Bool" + }, + { + "ordinal": 3, + "name": "owner", + "type_info": "Varchar" + }, + { + "ordinal": 4, + "name": "allowed_ips", + "type_info": "TextArray" + }, + { + "ordinal": 5, + "name": "admin", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + true, + true, + false, + true, + null, + false + ] + }, + "hash": "6bbf56bbc7b647daaba8dc5a4d49bffa976b5da8e8052638b8ee3e3c834dac27" +} diff --git a/backend/.sqlx/query-6c1798b9a60634e908852e65e7583a9bc7d8e6f97559b1f6a2a069a073b7e48c.json b/backend/.sqlx/query-6c1798b9a60634e908852e65e7583a9bc7d8e6f97559b1f6a2a069a073b7e48c.json new file mode 100644 index 0000000000..7ba9833338 --- /dev/null +++ b/backend/.sqlx/query-6c1798b9a60634e908852e65e7583a9bc7d8e6f97559b1f6a2a069a073b7e48c.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO resource (workspace_id, path, value, description, resource_type, extra_perms, edited_at, created_by, labels)\n SELECT $2, path,\n CASE WHEN $3::text IS NOT NULL AND resource_type = 'ai_agent'\n AND jsonb_typeof(value) = 'object' AND value ? 'on_behalf_of'\n THEN jsonb_set(value, '{on_behalf_of}', to_jsonb($3::text))\n ELSE value END,\n description, resource_type, extra_perms, edited_at, created_by, labels\n FROM resource\n WHERE workspace_id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Varchar", + "Text" + ] + }, + "nullable": [] + }, + "hash": "6c1798b9a60634e908852e65e7583a9bc7d8e6f97559b1f6a2a069a073b7e48c" +} diff --git a/backend/.sqlx/query-6f9c95e209ad7161ec02b70c156a31e640ed9e8c7fcdc5bd2da94bc5728f0455.json b/backend/.sqlx/query-6f9c95e209ad7161ec02b70c156a31e640ed9e8c7fcdc5bd2da94bc5728f0455.json new file mode 100644 index 0000000000..70ada31c5b --- /dev/null +++ b/backend/.sqlx/query-6f9c95e209ad7161ec02b70c156a31e640ed9e8c7fcdc5bd2da94bc5728f0455.json @@ -0,0 +1,47 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT j.id, j.tag, j.kind = 'flownode' AS \"is_node!\",\n COALESCE(s.flow_status, c.flow_status) AS flow_status,\n COALESCE(j.raw_flow, fv.value, fn.flow) AS flow\n FROM v2_job j\n LEFT JOIN v2_job_status s ON s.id = j.id\n LEFT JOIN v2_job_completed c ON c.id = j.id\n LEFT JOIN flow_version fv\n ON j.raw_flow IS NULL AND j.kind = 'flow' AND fv.id = j.runnable_id\n LEFT JOIN flow_node fn\n ON j.raw_flow IS NULL AND j.kind = 'flownode' AND fn.id = j.runnable_id\n WHERE j.id = ANY($1) AND j.workspace_id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "tag", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "is_node!", + "type_info": "Bool" + }, + { + "ordinal": 3, + "name": "flow_status", + "type_info": "Jsonb" + }, + { + "ordinal": 4, + "name": "flow", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "UuidArray", + "Text" + ] + }, + "nullable": [ + false, + false, + null, + null, + null + ] + }, + "hash": "6f9c95e209ad7161ec02b70c156a31e640ed9e8c7fcdc5bd2da94bc5728f0455" +} diff --git a/backend/.sqlx/query-706f2227e34971d22a577b33f6aaa7f5755da9997419c4a9d07b30d4da318bea.json b/backend/.sqlx/query-706f2227e34971d22a577b33f6aaa7f5755da9997419c4a9d07b30d4da318bea.json deleted file mode 100644 index 7c305d1e7a..0000000000 --- a/backend/.sqlx/query-706f2227e34971d22a577b33f6aaa7f5755da9997419c4a9d07b30d4da318bea.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO script (\n workspace_id, hash, path, parent_hashes, summary, description, content,\n created_by, created_at, archived, schema, deleted, is_template,\n extra_perms, lock, lock_error_logs, language, kind, tag,\n envs, concurrent_limit, concurrency_time_window_s, cache_ttl,\n dedicated_worker, ws_error_handler_muted, priority, timeout,\n delete_after_use, delete_after_secs, restart_unless_cancelled, concurrency_key,\n visible_to_runner_only, auto_kind, codebase, has_preprocessor,\n on_behalf_of, on_behalf_of_email, assets, modules, job_token_scopes\n )\n SELECT\n $1, hash, path, parent_hashes, summary, description, content,\n created_by, created_at, archived, schema, deleted, is_template,\n extra_perms, lock, lock_error_logs, language, kind, tag,\n envs, concurrent_limit, concurrency_time_window_s, cache_ttl,\n dedicated_worker, ws_error_handler_muted, priority, timeout,\n delete_after_use, delete_after_secs, restart_unless_cancelled, concurrency_key,\n visible_to_runner_only, auto_kind, codebase, has_preprocessor,\n -- Same three forms and the same prefix-first rule as permissioned_as_exists,\n -- superadmin fallback included: one acting outside their workspaces has no usr\n -- row but still authenticates.\n CASE WHEN on_behalf_of LIKE 'u/%' THEN\n (SELECT on_behalf_of WHERE EXISTS (\n SELECT 1 FROM usr u WHERE u.workspace_id = $1::varchar\n AND u.username = substring(on_behalf_of from 3)\n UNION ALL\n SELECT 1 FROM password p WHERE p.super_admin\n AND (p.username = substring(on_behalf_of from 3)\n OR p.email = substring(on_behalf_of from 3))))\n WHEN on_behalf_of LIKE 'g/%' THEN\n (SELECT on_behalf_of WHERE EXISTS (\n SELECT 1 FROM group_ g WHERE g.workspace_id = $1::varchar\n AND g.name = substring(on_behalf_of from 3)))\n ELSE\n (SELECT on_behalf_of WHERE EXISTS (\n SELECT 1 FROM usr u WHERE u.workspace_id = $1::varchar\n AND u.username = on_behalf_of\n UNION ALL\n SELECT 1 FROM password p WHERE p.email = on_behalf_of\n AND p.super_admin))\n END, on_behalf_of_email, assets, modules, job_token_scopes\n FROM script\n WHERE workspace_id = $2", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Varchar", - "Text" - ] - }, - "nullable": [] - }, - "hash": "706f2227e34971d22a577b33f6aaa7f5755da9997419c4a9d07b30d4da318bea" -} diff --git a/backend/.sqlx/query-7209d20f905f1dd81479e91c5748fcd59ddabaa0ad68e1ac74313948ce1457d1.json b/backend/.sqlx/query-7209d20f905f1dd81479e91c5748fcd59ddabaa0ad68e1ac74313948ce1457d1.json new file mode 100644 index 0000000000..dc132b1f20 --- /dev/null +++ b/backend/.sqlx/query-7209d20f905f1dd81479e91c5748fcd59ddabaa0ad68e1ac74313948ce1457d1.json @@ -0,0 +1,25 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO token\n (token_hash, token_prefix, token, email, label, expiration, super_admin, scopes, workspace_id, read_only, allowed_ips, admin)\n SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::text[]::cidr[], $12\n WHERE $9::varchar IS NULL OR NOT EXISTS(\n SELECT 1 FROM workspace WHERE id = $9 AND deleted = true\n )", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Timestamptz", + "Bool", + "TextArray", + "Varchar", + "Bool", + "TextArray", + "Bool" + ] + }, + "nullable": [] + }, + "hash": "7209d20f905f1dd81479e91c5748fcd59ddabaa0ad68e1ac74313948ce1457d1" +} diff --git a/backend/.sqlx/query-756524a33cf4923bb0b2a037930faf2f63e8b74389fd543d3b1fbea114706bbd.json b/backend/.sqlx/query-756524a33cf4923bb0b2a037930faf2f63e8b74389fd543d3b1fbea114706bbd.json new file mode 100644 index 0000000000..083a05527e --- /dev/null +++ b/backend/.sqlx/query-756524a33cf4923bb0b2a037930faf2f63e8b74389fd543d3b1fbea114706bbd.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT 1 FROM variable WHERE path = $1 AND workspace_id = $2 FOR UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "?column?", + "type_info": "Int4" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "756524a33cf4923bb0b2a037930faf2f63e8b74389fd543d3b1fbea114706bbd" +} diff --git a/backend/.sqlx/query-75d1618e12c4dfe5e9632ba8dc45b5aeb572e51ebd0732e6ebf80197acb3e577.json b/backend/.sqlx/query-75d1618e12c4dfe5e9632ba8dc45b5aeb572e51ebd0732e6ebf80197acb3e577.json deleted file mode 100644 index 817a13cb2f..0000000000 --- a/backend/.sqlx/query-75d1618e12c4dfe5e9632ba8dc45b5aeb572e51ebd0732e6ebf80197acb3e577.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT EXISTS (\n SELECT 1 FROM v2_job_completed c JOIN v2_job j USING (id)\n WHERE j.workspace_id = $2\n AND c.started_at > now() - interval '3 hours'\n AND c.result @> ('{\"s3\":\"' || $1 || '\"}')::jsonb\n AND j.trigger_kind = 'app'\n AND j.trigger = $3\n AND j.created_by = $4\n )", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "exists", - "type_info": "Bool" - } - ], - "parameters": { - "Left": [ - "Text", - "Text", - "Text", - "Text" - ] - }, - "nullable": [ - null - ] - }, - "hash": "75d1618e12c4dfe5e9632ba8dc45b5aeb572e51ebd0732e6ebf80197acb3e577" -} diff --git a/backend/.sqlx/query-7856dbf515932a2aa31e2124f5cc845a8d8da9e32e2a5b666a220398c76d1266.json b/backend/.sqlx/query-7856dbf515932a2aa31e2124f5cc845a8d8da9e32e2a5b666a220398c76d1266.json new file mode 100644 index 0000000000..f3d5b0a1aa --- /dev/null +++ b/backend/.sqlx/query-7856dbf515932a2aa31e2124f5cc845a8d8da9e32e2a5b666a220398c76d1266.json @@ -0,0 +1,32 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO account (workspace_id, client, expires_at, refresh_token, grant_type, cc_client_id, cc_client_secret, cc_token_url, mcp_server_url, scopes, is_workspace_integration) VALUES ($1, $2, now() + ($3 || ' seconds')::interval, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING id", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Int4" + } + ], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Text", + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Text", + "TextArray", + "Bool" + ] + }, + "nullable": [ + false + ] + }, + "hash": "7856dbf515932a2aa31e2124f5cc845a8d8da9e32e2a5b666a220398c76d1266" +} diff --git a/backend/.sqlx/query-78d53c53d22bdd8948a3375a19a2b3a87eb50150eb7b6888bc32a9d48a5ad21f.json b/backend/.sqlx/query-78d53c53d22bdd8948a3375a19a2b3a87eb50150eb7b6888bc32a9d48a5ad21f.json new file mode 100644 index 0000000000..0130589087 --- /dev/null +++ b/backend/.sqlx/query-78d53c53d22bdd8948a3375a19a2b3a87eb50150eb7b6888bc32a9d48a5ad21f.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO script (\n workspace_id, hash, path, parent_hashes, summary, description, content,\n created_by, created_at, archived, schema, deleted, is_template,\n extra_perms, lock, lock_error_logs, language, kind, tag,\n envs, concurrent_limit, concurrency_time_window_s, cache_ttl,\n dedicated_worker, ws_error_handler_muted, priority, timeout,\n delete_after_use, delete_after_secs, restart_unless_cancelled, concurrency_key,\n visible_to_runner_only, auto_kind, codebase, has_preprocessor,\n on_behalf_of, on_behalf_of_email, assets, modules, job_token_scopes, labels\n )\n SELECT\n $1, hash, path, parent_hashes, summary, description, content,\n created_by, created_at, archived, schema, deleted, is_template,\n extra_perms, lock, lock_error_logs, language, kind, tag,\n envs, concurrent_limit, concurrency_time_window_s, cache_ttl,\n dedicated_worker, ws_error_handler_muted, priority, timeout,\n delete_after_use, delete_after_secs, restart_unless_cancelled, concurrency_key,\n visible_to_runner_only, auto_kind, codebase, has_preprocessor,\n -- Same three forms and the same prefix-first rule as permissioned_as_exists,\n -- superadmin fallback included: one acting outside their workspaces has no usr\n -- row but still authenticates.\n CASE WHEN on_behalf_of LIKE 'u/%' THEN\n (SELECT on_behalf_of WHERE EXISTS (\n SELECT 1 FROM usr u WHERE u.workspace_id = $1::varchar\n AND u.username = substring(on_behalf_of from 3)\n UNION ALL\n SELECT 1 FROM password p WHERE p.super_admin\n AND (p.username = substring(on_behalf_of from 3)\n OR p.email = substring(on_behalf_of from 3))))\n WHEN on_behalf_of LIKE 'g/%' THEN\n (SELECT on_behalf_of WHERE EXISTS (\n SELECT 1 FROM group_ g WHERE g.workspace_id = $1::varchar\n AND g.name = substring(on_behalf_of from 3)))\n ELSE\n (SELECT on_behalf_of WHERE EXISTS (\n SELECT 1 FROM usr u WHERE u.workspace_id = $1::varchar\n AND u.username = on_behalf_of\n UNION ALL\n SELECT 1 FROM password p WHERE p.email = on_behalf_of\n AND p.super_admin))\n END, on_behalf_of_email, assets, modules, job_token_scopes, labels\n FROM script\n WHERE workspace_id = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Text" + ] + }, + "nullable": [] + }, + "hash": "78d53c53d22bdd8948a3375a19a2b3a87eb50150eb7b6888bc32a9d48a5ad21f" +} diff --git a/backend/.sqlx/query-79ad082adcef4e3dd4745bff5f498889cdd0f5365bd43442ac745997f1a4173c.json b/backend/.sqlx/query-79ad082adcef4e3dd4745bff5f498889cdd0f5365bd43442ac745997f1a4173c.json new file mode 100644 index 0000000000..960a40a9cd --- /dev/null +++ b/backend/.sqlx/query-79ad082adcef4e3dd4745bff5f498889cdd0f5365bd43442ac745997f1a4173c.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE concurrency_key SET released_at = $2 WHERE job_id = $1 AND released_at IS NULL", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Timestamptz" + ] + }, + "nullable": [] + }, + "hash": "79ad082adcef4e3dd4745bff5f498889cdd0f5365bd43442ac745997f1a4173c" +} diff --git a/backend/.sqlx/query-79eed97c7119a64f00b85679c491a5001d75fa977a6f57d806d0d1fb28564a23.json b/backend/.sqlx/query-79eed97c7119a64f00b85679c491a5001d75fa977a6f57d806d0d1fb28564a23.json new file mode 100644 index 0000000000..6ffe242aa3 --- /dev/null +++ b/backend/.sqlx/query-79eed97c7119a64f00b85679c491a5001d75fa977a6f57d806d0d1fb28564a23.json @@ -0,0 +1,149 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT resource.workspace_id, resource.path, resource.value, resource.description,\n resource.resource_type, resource.extra_perms, resource.created_by, resource.edited_at,\n resource.labels,\n folder_labels(resource.workspace_id, resource.path) as \"inherited_labels?\",\n (now() > account.expires_at) as is_expired, account.refresh_token != '' as is_refreshed,\n account.refresh_error, account.scopes as \"scopes?\", account.client as \"client?\",\n account.is_workspace_integration as \"is_workspace_integration?\",\n variable.path IS NOT NULL as is_linked,\n variable.is_oauth as \"is_oauth?\",\n variable.account,\n ws_specific.path IS NOT NULL as ws_specific,\n null::bool as draft_only,\n null::bool as is_draft\n FROM resource\n LEFT JOIN variable ON variable.path = resource.path AND variable.workspace_id = $2\n LEFT JOIN account ON variable.account = account.id AND account.workspace_id = $2\n LEFT JOIN ws_specific ON ws_specific.path = resource.path AND ws_specific.workspace_id = $2 AND ws_specific.item_kind = 'resource'\n WHERE resource.path = $1 AND resource.workspace_id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "path", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "value", + "type_info": "Jsonb" + }, + { + "ordinal": 3, + "name": "description", + "type_info": "Text" + }, + { + "ordinal": 4, + "name": "resource_type", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "extra_perms", + "type_info": "Jsonb" + }, + { + "ordinal": 6, + "name": "created_by", + "type_info": "Varchar" + }, + { + "ordinal": 7, + "name": "edited_at", + "type_info": "Timestamptz" + }, + { + "ordinal": 8, + "name": "labels", + "type_info": "TextArray" + }, + { + "ordinal": 9, + "name": "inherited_labels?", + "type_info": "TextArray" + }, + { + "ordinal": 10, + "name": "is_expired", + "type_info": "Bool" + }, + { + "ordinal": 11, + "name": "is_refreshed", + "type_info": "Bool" + }, + { + "ordinal": 12, + "name": "refresh_error", + "type_info": "Text" + }, + { + "ordinal": 13, + "name": "scopes?", + "type_info": "TextArray" + }, + { + "ordinal": 14, + "name": "client?", + "type_info": "Varchar" + }, + { + "ordinal": 15, + "name": "is_workspace_integration?", + "type_info": "Bool" + }, + { + "ordinal": 16, + "name": "is_linked", + "type_info": "Bool" + }, + { + "ordinal": 17, + "name": "is_oauth?", + "type_info": "Bool" + }, + { + "ordinal": 18, + "name": "account", + "type_info": "Int4" + }, + { + "ordinal": 19, + "name": "ws_specific", + "type_info": "Bool" + }, + { + "ordinal": 20, + "name": "draft_only", + "type_info": "Bool" + }, + { + "ordinal": 21, + "name": "is_draft", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + false, + true, + true, + false, + false, + true, + true, + true, + null, + null, + null, + true, + true, + false, + false, + null, + false, + true, + null, + null, + null + ] + }, + "hash": "79eed97c7119a64f00b85679c491a5001d75fa977a6f57d806d0d1fb28564a23" +} diff --git a/backend/.sqlx/query-b7335ac24702c86fbb4ab95916a6aa1648082287b09122755df2462dc71ce831.json b/backend/.sqlx/query-7af495acd76616fcb91b058b12e852363a314b39a7aa0ee2beaeab549378e7c0.json similarity index 71% rename from backend/.sqlx/query-b7335ac24702c86fbb4ab95916a6aa1648082287b09122755df2462dc71ce831.json rename to backend/.sqlx/query-7af495acd76616fcb91b058b12e852363a314b39a7aa0ee2beaeab549378e7c0.json index 7f90d5ac1f..e1b3a45b58 100644 --- a/backend/.sqlx/query-b7335ac24702c86fbb4ab95916a6aa1648082287b09122755df2462dc71ce831.json +++ b/backend/.sqlx/query-7af495acd76616fcb91b058b12e852363a314b39a7aa0ee2beaeab549378e7c0.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n WITH j AS (\n SELECT \n raw_flow->>'concurrency_key' as concurrency_key, \n raw_flow->>'concurrency_time_window_s' as concurrency_time_window_s,\n raw_flow->>'concurrency_limit' as concurrent_limit,\n runnable_path, \n runnable_id as version FROM v2_job\n WHERE id = $1\n )\n SELECT tag, j.concurrency_key, j.concurrency_time_window_s::int, j.concurrent_limit::int, j.version\n FROM flow, j\n WHERE path = j.runnable_path\n ", + "query": "\n WITH j AS (\n SELECT \n raw_flow->>'concurrency_key' as concurrency_key, \n raw_flow->>'concurrency_time_window_s' as concurrency_time_window_s,\n raw_flow->>'concurrency_limit' as concurrent_limit,\n runnable_path, \n workspace_id,\n runnable_id as version FROM v2_job\n WHERE id = $1\n )\n SELECT tag, j.concurrency_key, j.concurrency_time_window_s::int, j.concurrent_limit::int, j.version\n FROM flow, j\n WHERE path = j.runnable_path AND flow.workspace_id = j.workspace_id\n ", "describe": { "columns": [ { @@ -42,5 +42,5 @@ true ] }, - "hash": "b7335ac24702c86fbb4ab95916a6aa1648082287b09122755df2462dc71ce831" + "hash": "7af495acd76616fcb91b058b12e852363a314b39a7aa0ee2beaeab549378e7c0" } diff --git a/backend/.sqlx/query-7c420846f546d4307cc503e3a6eafdad0b565360247a644ef7777eecd3e99e1a.json b/backend/.sqlx/query-7c420846f546d4307cc503e3a6eafdad0b565360247a644ef7777eecd3e99e1a.json new file mode 100644 index 0000000000..94590c4b72 --- /dev/null +++ b/backend/.sqlx/query-7c420846f546d4307cc503e3a6eafdad0b565360247a644ef7777eecd3e99e1a.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO token\n (token_hash, token_prefix, token, email, label, expiration, super_admin, allowed_ips,\n workspace_id, admin)\n SELECT $1, $2, $3, $4, $5, $6, $7, $8::text[]::cidr[], $9, $10\n WHERE $9::varchar IS NULL OR NOT EXISTS(\n SELECT 1 FROM workspace WHERE id = $9 AND deleted = true\n )", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Timestamptz", + "Bool", + "TextArray", + "Varchar", + "Bool" + ] + }, + "nullable": [] + }, + "hash": "7c420846f546d4307cc503e3a6eafdad0b565360247a644ef7777eecd3e99e1a" +} diff --git a/backend/.sqlx/query-7c70080e4d6248c9593ebfe8c3c3a09252f353124ddad863100f3598f6241fb1.json b/backend/.sqlx/query-7c70080e4d6248c9593ebfe8c3c3a09252f353124ddad863100f3598f6241fb1.json new file mode 100644 index 0000000000..984e733192 --- /dev/null +++ b/backend/.sqlx/query-7c70080e4d6248c9593ebfe8c3c3a09252f353124ddad863100f3598f6241fb1.json @@ -0,0 +1,90 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT label, token_prefix AS \"token_prefix!\", expiration,\n created_at AS \"created_at!\", last_used_at AS \"last_used_at!\", scopes, workspace_id,\n read_only AS \"read_only!\", allowed_ips::text[] AS allowed_ips,\n admin AS \"admin!\", super_admin AS \"super_admin!\", risks AS \"risks!\"\n FROM token_risk WHERE email = $1 AND (label != 'ephemeral-script' OR label IS NULL)\n ORDER BY created_at DESC LIMIT $2 OFFSET $3", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "label", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "token_prefix!", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "expiration", + "type_info": "Timestamptz" + }, + { + "ordinal": 3, + "name": "created_at!", + "type_info": "Timestamptz" + }, + { + "ordinal": 4, + "name": "last_used_at!", + "type_info": "Timestamptz" + }, + { + "ordinal": 5, + "name": "scopes", + "type_info": "TextArray" + }, + { + "ordinal": 6, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 7, + "name": "read_only!", + "type_info": "Bool" + }, + { + "ordinal": 8, + "name": "allowed_ips", + "type_info": "TextArray" + }, + { + "ordinal": 9, + "name": "admin!", + "type_info": "Bool" + }, + { + "ordinal": 10, + "name": "super_admin!", + "type_info": "Bool" + }, + { + "ordinal": 11, + "name": "risks!", + "type_info": "TextArray" + } + ], + "parameters": { + "Left": [ + "Text", + "Int8", + "Int8" + ] + }, + "nullable": [ + true, + true, + true, + true, + true, + true, + true, + true, + null, + true, + true, + true + ] + }, + "hash": "7c70080e4d6248c9593ebfe8c3c3a09252f353124ddad863100f3598f6241fb1" +} diff --git a/backend/.sqlx/query-80a33efd3fd3e9bb447568f7e51aecdedadcbf2aaf65820b91793accbd695032.json b/backend/.sqlx/query-80a33efd3fd3e9bb447568f7e51aecdedadcbf2aaf65820b91793accbd695032.json new file mode 100644 index 0000000000..f05f18da31 --- /dev/null +++ b/backend/.sqlx/query-80a33efd3fd3e9bb447568f7e51aecdedadcbf2aaf65820b91793accbd695032.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE password SET totp_failed_attempts = 0, totp_failed_since = NULL WHERE email = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "80a33efd3fd3e9bb447568f7e51aecdedadcbf2aaf65820b91793accbd695032" +} diff --git a/backend/.sqlx/query-8449b974fcedf52f9746ae6fd6a052977a44f8b068285949cef8b6ac3ecd6dce.json b/backend/.sqlx/query-8449b974fcedf52f9746ae6fd6a052977a44f8b068285949cef8b6ac3ecd6dce.json new file mode 100644 index 0000000000..b317570b13 --- /dev/null +++ b/backend/.sqlx/query-8449b974fcedf52f9746ae6fd6a052977a44f8b068285949cef8b6ac3ecd6dce.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT totp_secret IS NOT NULL AS \"enrolled!\" FROM password\n WHERE email = $1 AND login_type = 'password'", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "enrolled!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "8449b974fcedf52f9746ae6fd6a052977a44f8b068285949cef8b6ac3ecd6dce" +} diff --git a/backend/.sqlx/query-850fa2b74ada0abebf3905a8596c13dcaae05ce1e15146c77c864c2ad6abbcf5.json b/backend/.sqlx/query-850fa2b74ada0abebf3905a8596c13dcaae05ce1e15146c77c864c2ad6abbcf5.json new file mode 100644 index 0000000000..dfa993f557 --- /dev/null +++ b/backend/.sqlx/query-850fa2b74ada0abebf3905a8596c13dcaae05ce1e15146c77c864c2ad6abbcf5.json @@ -0,0 +1,18 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE variable SET value = $3, account = $4, edited_by = $5, edited_at = now()\n WHERE workspace_id = $1 AND path = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text", + "Varchar", + "Int4", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "850fa2b74ada0abebf3905a8596c13dcaae05ce1e15146c77c864c2ad6abbcf5" +} diff --git a/backend/.sqlx/query-8728e856ad6ba82495890e466f5226b401927d6ada71f91e0a035f9945dbf036.json b/backend/.sqlx/query-8728e856ad6ba82495890e466f5226b401927d6ada71f91e0a035f9945dbf036.json new file mode 100644 index 0000000000..873a16c236 --- /dev/null +++ b/backend/.sqlx/query-8728e856ad6ba82495890e466f5226b401927d6ada71f91e0a035f9945dbf036.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT key FROM workspace_key WHERE workspace_id = $1 AND kind = 'cloud' FOR SHARE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "key", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "8728e856ad6ba82495890e466f5226b401927d6ada71f91e0a035f9945dbf036" +} diff --git a/backend/.sqlx/query-8b088d35a98d695c35d0ffe3ee3d104d2e4275bd1e9562927d591650382d510d.json b/backend/.sqlx/query-8b088d35a98d695c35d0ffe3ee3d104d2e4275bd1e9562927d591650382d510d.json new file mode 100644 index 0000000000..216c54a3f4 --- /dev/null +++ b/backend/.sqlx/query-8b088d35a98d695c35d0ffe3ee3d104d2e4275bd1e9562927d591650382d510d.json @@ -0,0 +1,57 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH v AS (\n SELECT c.result #> $3 AS r, created_by\n FROM v2_job_completed c JOIN v2_job USING (id)\n WHERE c.id = $1 AND c.workspace_id = $2 AND ($4::text[] IS NULL OR tag = ANY($4))\n )\n SELECT\n created_by AS \"created_by!\",\n jsonb_typeof(r) AS \"type\",\n length(r::text) AS \"length\",\n CASE WHEN jsonb_typeof(r) = 'object' THEN\n ARRAY(SELECT jsonb_object_keys(r) LIMIT $6)\n END AS \"keys\",\n CASE WHEN jsonb_typeof(r) = 'array' THEN jsonb_array_length(r) END AS \"item_count\",\n CASE WHEN jsonb_typeof(r) = 'array' THEN (\n SELECT jsonb_agg(jsonb_build_object(\n 'length', length(e::text),\n 'keys', CASE WHEN jsonb_typeof(e) = 'object' THEN\n to_jsonb(ARRAY(SELECT jsonb_object_keys(e) LIMIT $6))\n END\n ) ORDER BY i)\n FROM jsonb_array_elements(r) WITH ORDINALITY AS t(e, i)\n WHERE i <= $5\n ) END AS \"items: sqlx::types::Json>\"\n FROM v", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "created_by!", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "type", + "type_info": "Text" + }, + { + "ordinal": 2, + "name": "length", + "type_info": "Int4" + }, + { + "ordinal": 3, + "name": "keys", + "type_info": "TextArray" + }, + { + "ordinal": 4, + "name": "item_count", + "type_info": "Int4" + }, + { + "ordinal": 5, + "name": "items: sqlx::types::Json>", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text", + "TextArray", + "TextArray", + "Int8", + "Int8" + ] + }, + "nullable": [ + false, + null, + null, + null, + null, + null + ] + }, + "hash": "8b088d35a98d695c35d0ffe3ee3d104d2e4275bd1e9562927d591650382d510d" +} diff --git a/backend/.sqlx/query-8c8ab1f498ca1460d2b58d95c09af1e3230e8f7cfd7a49b4fec87110e31470fa.json b/backend/.sqlx/query-8c8ab1f498ca1460d2b58d95c09af1e3230e8f7cfd7a49b4fec87110e31470fa.json new file mode 100644 index 0000000000..6c1d8c0dde --- /dev/null +++ b/backend/.sqlx/query-8c8ab1f498ca1460d2b58d95c09af1e3230e8f7cfd7a49b4fec87110e31470fa.json @@ -0,0 +1,35 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT name, bypass_users, bypass_groups FROM workspace_protection_rule\n WHERE workspace_id = $1 AND (rules & $2) <> 0 ORDER BY name", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "bypass_users", + "type_info": "TextArray" + }, + { + "ordinal": 2, + "name": "bypass_groups", + "type_info": "TextArray" + } + ], + "parameters": { + "Left": [ + "Text", + "Int4" + ] + }, + "nullable": [ + false, + false, + false + ] + }, + "hash": "8c8ab1f498ca1460d2b58d95c09af1e3230e8f7cfd7a49b4fec87110e31470fa" +} diff --git a/backend/.sqlx/query-8f7b47cc91a6d520cf40787382f5d511eb8c9f096a7ef0fd9c13db8a88be0cf9.json b/backend/.sqlx/query-8f7b47cc91a6d520cf40787382f5d511eb8c9f096a7ef0fd9c13db8a88be0cf9.json new file mode 100644 index 0000000000..4dacfbddcf --- /dev/null +++ b/backend/.sqlx/query-8f7b47cc91a6d520cf40787382f5d511eb8c9f096a7ef0fd9c13db8a88be0cf9.json @@ -0,0 +1,65 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT token_hash, label, scopes, super_admin, admin,\n allowed_ips::text[] AS allowed_ips, expiration, workspace_id\n FROM token\n WHERE email = $1 AND token_prefix = $2\n AND (expiration IS NULL OR expiration > now())\n FOR UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "token_hash", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "label", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "scopes", + "type_info": "TextArray" + }, + { + "ordinal": 3, + "name": "super_admin", + "type_info": "Bool" + }, + { + "ordinal": 4, + "name": "admin", + "type_info": "Bool" + }, + { + "ordinal": 5, + "name": "allowed_ips", + "type_info": "TextArray" + }, + { + "ordinal": 6, + "name": "expiration", + "type_info": "Timestamptz" + }, + { + "ordinal": 7, + "name": "workspace_id", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + true, + true, + false, + false, + null, + true, + true + ] + }, + "hash": "8f7b47cc91a6d520cf40787382f5d511eb8c9f096a7ef0fd9c13db8a88be0cf9" +} diff --git a/backend/.sqlx/query-922caf8126ce91b0339b377a14860a0ef6183943eb452c4c9bb9de22a559e47d.json b/backend/.sqlx/query-922caf8126ce91b0339b377a14860a0ef6183943eb452c4c9bb9de22a559e47d.json new file mode 100644 index 0000000000..889f5916fd --- /dev/null +++ b/backend/.sqlx/query-922caf8126ce91b0339b377a14860a0ef6183943eb452c4c9bb9de22a559e47d.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE variable SET account = NULL WHERE workspace_id = $1 AND account = ANY($2)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Int4Array" + ] + }, + "nullable": [] + }, + "hash": "922caf8126ce91b0339b377a14860a0ef6183943eb452c4c9bb9de22a559e47d" +} diff --git a/backend/.sqlx/query-931ae8904481286bbc42f30ba8df35b3a687a894311e8d7d0b8e6f1e5a07797a.json b/backend/.sqlx/query-931ae8904481286bbc42f30ba8df35b3a687a894311e8d7d0b8e6f1e5a07797a.json new file mode 100644 index 0000000000..bd7c4be081 --- /dev/null +++ b/backend/.sqlx/query-931ae8904481286bbc42f30ba8df35b3a687a894311e8d7d0b8e6f1e5a07797a.json @@ -0,0 +1,37 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO audit_partitioned\n (workspace_id, username, operation, action_kind, resource, parameters, email, span,\n client_ip, user_agent, peer_ip, forwarded_for)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Varchar", + { + "Custom": { + "name": "action_kind", + "kind": { + "Enum": [ + "create", + "update", + "delete", + "execute" + ] + } + } + }, + "Varchar", + "Jsonb", + "Varchar", + "Varchar", + "Text", + "Text", + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "931ae8904481286bbc42f30ba8df35b3a687a894311e8d7d0b8e6f1e5a07797a" +} diff --git a/backend/.sqlx/query-96611797b0867dc967ab5076005e39141ff05981a14029714318b80ae97cc4fa.json b/backend/.sqlx/query-96611797b0867dc967ab5076005e39141ff05981a14029714318b80ae97cc4fa.json new file mode 100644 index 0000000000..cf37e33bc4 --- /dev/null +++ b/backend/.sqlx/query-96611797b0867dc967ab5076005e39141ff05981a14029714318b80ae97cc4fa.json @@ -0,0 +1,90 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT label, token_prefix AS \"token_prefix!\", expiration,\n created_at AS \"created_at!\", last_used_at AS \"last_used_at!\", scopes, workspace_id,\n read_only AS \"read_only!\", allowed_ips::text[] AS allowed_ips,\n admin AS \"admin!\", super_admin AS \"super_admin!\", risks AS \"risks!\"\n FROM token_risk WHERE email = $1\n ORDER BY created_at DESC LIMIT $2 OFFSET $3", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "label", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "token_prefix!", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "expiration", + "type_info": "Timestamptz" + }, + { + "ordinal": 3, + "name": "created_at!", + "type_info": "Timestamptz" + }, + { + "ordinal": 4, + "name": "last_used_at!", + "type_info": "Timestamptz" + }, + { + "ordinal": 5, + "name": "scopes", + "type_info": "TextArray" + }, + { + "ordinal": 6, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 7, + "name": "read_only!", + "type_info": "Bool" + }, + { + "ordinal": 8, + "name": "allowed_ips", + "type_info": "TextArray" + }, + { + "ordinal": 9, + "name": "admin!", + "type_info": "Bool" + }, + { + "ordinal": 10, + "name": "super_admin!", + "type_info": "Bool" + }, + { + "ordinal": 11, + "name": "risks!", + "type_info": "TextArray" + } + ], + "parameters": { + "Left": [ + "Text", + "Int8", + "Int8" + ] + }, + "nullable": [ + true, + true, + true, + true, + true, + true, + true, + true, + null, + true, + true, + true + ] + }, + "hash": "96611797b0867dc967ab5076005e39141ff05981a14029714318b80ae97cc4fa" +} diff --git a/backend/.sqlx/query-99acb6ee58e9289e5f10f535859290da9bd333a79aa71f0bc3118381aaeae465.json b/backend/.sqlx/query-99acb6ee58e9289e5f10f535859290da9bd333a79aa71f0bc3118381aaeae465.json new file mode 100644 index 0000000000..06d87660f8 --- /dev/null +++ b/backend/.sqlx/query-99acb6ee58e9289e5f10f535859290da9bd333a79aa71f0bc3118381aaeae465.json @@ -0,0 +1,40 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT client_id, client_name, redirect_uris, created_at FROM mcp_oauth_server_client\n WHERE client_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "client_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "client_name", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "redirect_uris", + "type_info": "TextArray" + }, + { + "ordinal": 3, + "name": "created_at", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false + ] + }, + "hash": "99acb6ee58e9289e5f10f535859290da9bd333a79aa71f0bc3118381aaeae465" +} diff --git a/backend/.sqlx/query-9b35fc71fa5994aa7db3b190c7389648ca885dc87ff1b105a35ba23572598504.json b/backend/.sqlx/query-9b35fc71fa5994aa7db3b190c7389648ca885dc87ff1b105a35ba23572598504.json new file mode 100644 index 0000000000..16ff07308d --- /dev/null +++ b/backend/.sqlx/query-9b35fc71fa5994aa7db3b190c7389648ca885dc87ff1b105a35ba23572598504.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS(SELECT 1 FROM script WHERE hash = $1 AND workspace_id = $2)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Int8", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "9b35fc71fa5994aa7db3b190c7389648ca885dc87ff1b105a35ba23572598504" +} diff --git a/backend/.sqlx/query-9c5b3df2be18b88c063a39df8be1bd0f3cceb1312e0856600ece549ab649df3b.json b/backend/.sqlx/query-9c5b3df2be18b88c063a39df8be1bd0f3cceb1312e0856600ece549ab649df3b.json new file mode 100644 index 0000000000..eff177139d --- /dev/null +++ b/backend/.sqlx/query-9c5b3df2be18b88c063a39df8be1bd0f3cceb1312e0856600ece549ab649df3b.json @@ -0,0 +1,30 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT 'scripts' AS \"domain!\", path AS \"path!\" FROM script WHERE workspace_id = $1 AND NOT archived\n AND starts_with(path, 'u/') AND NOT starts_with(path, $2) AND NOT extra_perms ?| $3\n UNION\n SELECT 'flows', path FROM flow WHERE workspace_id = $1 AND NOT archived\n AND starts_with(path, 'u/') AND NOT starts_with(path, $2) AND NOT extra_perms ?| $3\n UNION ALL\n SELECT 'apps', path FROM app WHERE workspace_id = $1\n AND starts_with(path, 'u/') AND NOT starts_with(path, $2) AND NOT extra_perms ?| $3\n UNION ALL\n SELECT 'resources', path FROM resource WHERE workspace_id = $1\n AND starts_with(path, 'u/') AND NOT starts_with(path, $2) AND NOT extra_perms ?| $3\n UNION ALL\n SELECT 'variables', path FROM variable WHERE workspace_id = $1\n AND starts_with(path, 'u/') AND NOT starts_with(path, $2) AND NOT extra_perms ?| $3\n LIMIT 10000", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "domain!", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "path!", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "TextArray" + ] + }, + "nullable": [ + null, + null + ] + }, + "hash": "9c5b3df2be18b88c063a39df8be1bd0f3cceb1312e0856600ece549ab649df3b" +} diff --git a/backend/.sqlx/query-d17645b5001d7f8da1dc451c5d35ea3c9346271b8404863256071cfdf884036a.json b/backend/.sqlx/query-9f1e9d7657c78e014792be95b6bf3d12945450fdfbd9f52e59617660ea20c4c3.json similarity index 50% rename from backend/.sqlx/query-d17645b5001d7f8da1dc451c5d35ea3c9346271b8404863256071cfdf884036a.json rename to backend/.sqlx/query-9f1e9d7657c78e014792be95b6bf3d12945450fdfbd9f52e59617660ea20c4c3.json index c3134373f6..475628940f 100644 --- a/backend/.sqlx/query-d17645b5001d7f8da1dc451c5d35ea3c9346271b8404863256071cfdf884036a.json +++ b/backend/.sqlx/query-9f1e9d7657c78e014792be95b6bf3d12945450fdfbd9f52e59617660ea20c4c3.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE token SET scopes = $1\n WHERE email = $2 AND token_prefix = $3\n AND (label IS NULL OR label <> 'guest_session')\n RETURNING token_prefix", + "query": "DELETE FROM token WHERE email = $1 AND token_prefix = $2 RETURNING token_prefix", "describe": { "columns": [ { @@ -11,7 +11,6 @@ ], "parameters": { "Left": [ - "TextArray", "Text", "Text" ] @@ -20,5 +19,5 @@ false ] }, - "hash": "d17645b5001d7f8da1dc451c5d35ea3c9346271b8404863256071cfdf884036a" + "hash": "9f1e9d7657c78e014792be95b6bf3d12945450fdfbd9f52e59617660ea20c4c3" } diff --git a/backend/.sqlx/query-a1657b30563ec08887fda54469febbc2a33fea44f9ffad3416ef3915a81c9cc7.json b/backend/.sqlx/query-a1657b30563ec08887fda54469febbc2a33fea44f9ffad3416ef3915a81c9cc7.json new file mode 100644 index 0000000000..41e2ccb340 --- /dev/null +++ b/backend/.sqlx/query-a1657b30563ec08887fda54469febbc2a33fea44f9ffad3416ef3915a81c9cc7.json @@ -0,0 +1,30 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT workspace_id, username FROM usr\n WHERE email = $1 AND is_admin AND NOT disabled\n AND ($2::text[] IS NULL OR workspace_id = ANY($2))\n ORDER BY workspace_id LIMIT $3", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "username", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "TextArray", + "Int8" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "a1657b30563ec08887fda54469febbc2a33fea44f9ffad3416ef3915a81c9cc7" +} diff --git a/backend/.sqlx/query-a2d0fb45dde296b7011a0cf8a9ae83f33736266736c0f0dd8113f0363db984b2.json b/backend/.sqlx/query-a2d0fb45dde296b7011a0cf8a9ae83f33736266736c0f0dd8113f0363db984b2.json new file mode 100644 index 0000000000..d0366e4fb4 --- /dev/null +++ b/backend/.sqlx/query-a2d0fb45dde296b7011a0cf8a9ae83f33736266736c0f0dd8113f0363db984b2.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE token SET expiration = $1, allowed_ips = $2::text[]::cidr[]\n WHERE token_hash = $3", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Timestamptz", + "TextArray", + "Text" + ] + }, + "nullable": [] + }, + "hash": "a2d0fb45dde296b7011a0cf8a9ae83f33736266736c0f0dd8113f0363db984b2" +} diff --git a/backend/.sqlx/query-a5ddda3592c30ad7ccb1bf4215bb5271e1563ce19cb252837f9e26d5b8502667.json b/backend/.sqlx/query-a5ddda3592c30ad7ccb1bf4215bb5271e1563ce19cb252837f9e26d5b8502667.json new file mode 100644 index 0000000000..8fcd0baca5 --- /dev/null +++ b/backend/.sqlx/query-a5ddda3592c30ad7ccb1bf4215bb5271e1563ce19cb252837f9e26d5b8502667.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT i.email FROM workspace_invite i\n JOIN password p ON p.email = i.email AND p.login_type = 'password'\n WHERE i.workspace_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "email", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "a5ddda3592c30ad7ccb1bf4215bb5271e1563ce19cb252837f9e26d5b8502667" +} diff --git a/backend/.sqlx/query-eafb6d792370bf4d42cb79d0264e2eaf32f8f756920bd9fe9b302cba8e7d8814.json b/backend/.sqlx/query-a7bd504d6e509cde3e2ab12597f7e09c9c3d3ca760fab7244510824b5c762d07.json similarity index 58% rename from backend/.sqlx/query-eafb6d792370bf4d42cb79d0264e2eaf32f8f756920bd9fe9b302cba8e7d8814.json rename to backend/.sqlx/query-a7bd504d6e509cde3e2ab12597f7e09c9c3d3ca760fab7244510824b5c762d07.json index b7cfa590d5..2836c7ff27 100644 --- a/backend/.sqlx/query-eafb6d792370bf4d42cb79d0264e2eaf32f8f756920bd9fe9b302cba8e7d8814.json +++ b/backend/.sqlx/query-a7bd504d6e509cde3e2ab12597f7e09c9c3d3ca760fab7244510824b5c762d07.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT l.id IS NOT NULL as \"has_lite!\",\n CASE WHEN $3::bigint IS NULL THEN NOT EXISTS (\n SELECT 1 FROM app_script s\n WHERE s.app = a.id AND s.code_sha256 = $4::text\n AND jsonb_path_exists(l.value, '$.**.inlineScript.id ? (@ == $id)',\n jsonb_build_object('id', s.id)))\n ELSE coalesce(jsonb_path_exists(l.value, '$.**.inlineScript.id ? (@ == $id)',\n jsonb_build_object('id', $3::bigint)), false)\n END as \"may_run!\"\n FROM app a\n LEFT JOIN app_version_lite l ON l.id = a.versions[array_upper(a.versions, 1)]\n WHERE a.path = $1 AND a.workspace_id = $2", + "query": "SELECT l.id IS NOT NULL as \"has_lite!\",\n CASE WHEN $3::bigint IS NULL THEN NOT EXISTS (\n SELECT 1 FROM app_script s\n WHERE s.app = a.id AND s.code_sha256 = $4::text\n AND jsonb_path_exists(l.value, '$.**.inlineScript.id ? (@ == $id)',\n jsonb_build_object('id', s.id)))\n ELSE coalesce(jsonb_path_exists(coalesce(l.value, v.value::jsonb),\n '$.**.inlineScript.id ? (@ == $id)',\n jsonb_build_object('id', $3::bigint)), false)\n END as \"may_run!\"\n FROM app a\n LEFT JOIN app_version_lite l ON l.id = a.versions[array_upper(a.versions, 1)]\n LEFT JOIN app_version v ON v.id = a.versions[array_upper(a.versions, 1)]\n WHERE a.path = $1 AND a.workspace_id = $2", "describe": { "columns": [ { @@ -27,5 +27,5 @@ null ] }, - "hash": "eafb6d792370bf4d42cb79d0264e2eaf32f8f756920bd9fe9b302cba8e7d8814" + "hash": "a7bd504d6e509cde3e2ab12597f7e09c9c3d3ca760fab7244510824b5c762d07" } diff --git a/backend/.sqlx/query-7f832370916794ab0e5645053688c24678f1519d49ee7263a86dba71d45b8e8c.json b/backend/.sqlx/query-a8785d44c4af680f862689707dbe0eb0ad0c741d035eea9b31166aed7ca394d4.json similarity index 69% rename from backend/.sqlx/query-7f832370916794ab0e5645053688c24678f1519d49ee7263a86dba71d45b8e8c.json rename to backend/.sqlx/query-a8785d44c4af680f862689707dbe0eb0ad0c741d035eea9b31166aed7ca394d4.json index 173d8f2281..9042cdbc33 100644 --- a/backend/.sqlx/query-7f832370916794ab0e5645053688c24678f1519d49ee7263a86dba71d45b8e8c.json +++ b/backend/.sqlx/query-a8785d44c4af680f862689707dbe0eb0ad0c741d035eea9b31166aed7ca394d4.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO token\n (token_hash, token_prefix, token, email, label, expiration, super_admin, scopes, read_only)\n VALUES ($1, $2, $3, $4, $5, now() + ($6 || ' seconds')::interval, $7, $8, $9)", + "query": "INSERT INTO token\n (token_hash, token_prefix, token, email, label, expiration, super_admin, scopes, read_only, admin)\n VALUES ($1, $2, $3, $4, $5, now() + ($6 || ' seconds')::interval, $7, $8, $9, true)", "describe": { "columns": [], "parameters": { @@ -18,5 +18,5 @@ }, "nullable": [] }, - "hash": "7f832370916794ab0e5645053688c24678f1519d49ee7263a86dba71d45b8e8c" + "hash": "a8785d44c4af680f862689707dbe0eb0ad0c741d035eea9b31166aed7ca394d4" } diff --git a/backend/.sqlx/query-ac09d8de92d8e1ee9b463b87b2374e11ba46e9b392414282d2d67161a6544d11.json b/backend/.sqlx/query-a8f41490f55dea4b7f5497111d925ac5be5518831a9896c3949d32fe3eda0f3e.json similarity index 61% rename from backend/.sqlx/query-ac09d8de92d8e1ee9b463b87b2374e11ba46e9b392414282d2d67161a6544d11.json rename to backend/.sqlx/query-a8f41490f55dea4b7f5497111d925ac5be5518831a9896c3949d32fe3eda0f3e.json index 4d362ac045..160cdedffd 100644 --- a/backend/.sqlx/query-ac09d8de92d8e1ee9b463b87b2374e11ba46e9b392414282d2d67161a6544d11.json +++ b/backend/.sqlx/query-a8f41490f55dea4b7f5497111d925ac5be5518831a9896c3949d32fe3eda0f3e.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT app.summary, app.policy, app_version.value, app_version.raw_app\n FROM app\n JOIN app_version\n ON app_version.id = app.versions[array_upper(app.versions, 1)]\n WHERE app.workspace_id = $1 AND app.path = $2", + "query": "SELECT app.summary, app.policy, app_version.value, app_version.raw_app, app.labels\n FROM app\n JOIN app_version\n ON app_version.id = app.versions[array_upper(app.versions, 1)]\n WHERE app.workspace_id = $1 AND app.path = $2", "describe": { "columns": [ { @@ -22,6 +22,11 @@ "ordinal": 3, "name": "raw_app", "type_info": "Bool" + }, + { + "ordinal": 4, + "name": "labels", + "type_info": "TextArray" } ], "parameters": { @@ -34,8 +39,9 @@ false, false, false, - false + false, + true ] }, - "hash": "ac09d8de92d8e1ee9b463b87b2374e11ba46e9b392414282d2d67161a6544d11" + "hash": "a8f41490f55dea4b7f5497111d925ac5be5518831a9896c3949d32fe3eda0f3e" } diff --git a/backend/.sqlx/query-809a2dd647ddfc6fa79ca2c9039e4ebfc4b2880600a03b82e60b89c4a1fd5cc8.json b/backend/.sqlx/query-ab305b4e020220ba25c5c8263cb569991adb42acea00b109c74eb16bd8361dd6.json similarity index 50% rename from backend/.sqlx/query-809a2dd647ddfc6fa79ca2c9039e4ebfc4b2880600a03b82e60b89c4a1fd5cc8.json rename to backend/.sqlx/query-ab305b4e020220ba25c5c8263cb569991adb42acea00b109c74eb16bd8361dd6.json index cb33edacdf..aaa6f85e09 100644 --- a/backend/.sqlx/query-809a2dd647ddfc6fa79ca2c9039e4ebfc4b2880600a03b82e60b89c4a1fd5cc8.json +++ b/backend/.sqlx/query-ab305b4e020220ba25c5c8263cb569991adb42acea00b109c74eb16bd8361dd6.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO variable (workspace_id, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at, value_valid_until)\n SELECT $2, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at, value_valid_until\n FROM variable\n WHERE workspace_id = $1", + "query": "INSERT INTO variable (workspace_id, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at, value_valid_until, labels)\n SELECT $2, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at, value_valid_until, labels\n FROM variable\n WHERE workspace_id = $1", "describe": { "columns": [], "parameters": { @@ -11,5 +11,5 @@ }, "nullable": [] }, - "hash": "809a2dd647ddfc6fa79ca2c9039e4ebfc4b2880600a03b82e60b89c4a1fd5cc8" + "hash": "ab305b4e020220ba25c5c8263cb569991adb42acea00b109c74eb16bd8361dd6" } diff --git a/backend/.sqlx/query-b051ae8494073bc988dd272b2264520f36048ab3d12fe47652a854a41ddce1b0.json b/backend/.sqlx/query-b051ae8494073bc988dd272b2264520f36048ab3d12fe47652a854a41ddce1b0.json new file mode 100644 index 0000000000..7b16e81af2 --- /dev/null +++ b/backend/.sqlx/query-b051ae8494073bc988dd272b2264520f36048ab3d12fe47652a854a41ddce1b0.json @@ -0,0 +1,26 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (\n SELECT 1 FROM v2_job_completed c JOIN v2_job j USING (id)\n WHERE j.workspace_id = $2\n AND c.started_at > now() - interval '3 hours'\n AND j.trigger_kind = 'app'\n AND j.trigger = $3\n AND j.created_by = $4\n AND EXISTS (\n SELECT 1 FROM jsonb_array_elements(CASE jsonb_typeof(c.result)\n WHEN 'array' THEN c.result ELSE jsonb_build_array(c.result) END) o\n WHERE o->>'s3' = $1 AND o->>'storage' IS NOT DISTINCT FROM $5\n )\n )", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Text", + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "b051ae8494073bc988dd272b2264520f36048ab3d12fe47652a854a41ddce1b0" +} diff --git a/backend/.sqlx/query-b277825c1a82eebac652f4fcd19c91c3737cbc98cc8e5dd5e7bb50a802efad96.json b/backend/.sqlx/query-b277825c1a82eebac652f4fcd19c91c3737cbc98cc8e5dd5e7bb50a802efad96.json new file mode 100644 index 0000000000..652cd82d88 --- /dev/null +++ b/backend/.sqlx/query-b277825c1a82eebac652f4fcd19c91c3737cbc98cc8e5dd5e7bb50a802efad96.json @@ -0,0 +1,42 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH bounds AS (\n SELECT ($2::bigint % 4294967296)::text::xid AS prev_xid,\n ($3::bigint % 4294967296)::text::xid AS cur_xid,\n $1::timestamptz AS ts_floor\n ),\n batch AS (\n SELECT workspace_id, id, timestamp, username, operation,\n action_kind::text AS action_kind, resource, parameters, email, span,\n client_ip, user_agent, peer_ip, forwarded_for\n FROM audit_partitioned, bounds b\n WHERE timestamp >= b.ts_floor\n AND age(xmin) > age(b.cur_xid)\n AND age(xmin) <= age(b.prev_xid)\n ORDER BY id\n )\n SELECT to_char(timestamp AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS \"day!\",\n string_agg(row_to_json(batch)::text, E'\\n' ORDER BY id) AS \"ndjson!\",\n max(id) AS \"max_id!\",\n max(timestamp) AS \"max_ts!\"\n FROM batch\n GROUP BY 1\n ORDER BY 1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "day!", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "ndjson!", + "type_info": "Text" + }, + { + "ordinal": 2, + "name": "max_id!", + "type_info": "Int8" + }, + { + "ordinal": 3, + "name": "max_ts!", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [ + "Timestamptz", + "Int8", + "Int8" + ] + }, + "nullable": [ + null, + null, + null, + null + ] + }, + "hash": "b277825c1a82eebac652f4fcd19c91c3737cbc98cc8e5dd5e7bb50a802efad96" +} diff --git a/backend/.sqlx/query-b30fb28004897cd1d201a416cdabf124a055eb44b3c5892fd18ff7baf6010ae9.json b/backend/.sqlx/query-b30fb28004897cd1d201a416cdabf124a055eb44b3c5892fd18ff7baf6010ae9.json deleted file mode 100644 index c15e0edb33..0000000000 --- a/backend/.sqlx/query-b30fb28004897cd1d201a416cdabf124a055eb44b3c5892fd18ff7baf6010ae9.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE token SET label = $1\n WHERE email = $2 AND token_prefix = $3\n AND (label IS NULL OR (\n label <> 'session'\n AND label <> 'guest_session'\n AND lower(label) NOT LIKE 'ephemeral%'\n AND label <> 'debugger-token'\n AND label NOT LIKE 'mcp-oauth-%'\n AND NOT starts_with(label, 'embed_app:')\n AND NOT starts_with(label, 'sdk_app:')\n AND NOT starts_with(label, 'impersonation:')\n AND NOT starts_with(label, 'cli-login:')\n AND NOT starts_with(label, 'remote-deploy:')\n ))\n RETURNING token_prefix", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "token_prefix", - "type_info": "Varchar" - } - ], - "parameters": { - "Left": [ - "Varchar", - "Text", - "Text" - ] - }, - "nullable": [ - false - ] - }, - "hash": "b30fb28004897cd1d201a416cdabf124a055eb44b3c5892fd18ff7baf6010ae9" -} diff --git a/backend/.sqlx/query-30f69fd4baef17716d26cc59bf6369d6768972478def50010f680103d7c4281b.json b/backend/.sqlx/query-b7ecb69c99a1c840c400340c51e0a1b30410e587cf35d9488c5e5f4fc8c3ab58.json similarity index 70% rename from backend/.sqlx/query-30f69fd4baef17716d26cc59bf6369d6768972478def50010f680103d7c4281b.json rename to backend/.sqlx/query-b7ecb69c99a1c840c400340c51e0a1b30410e587cf35d9488c5e5f4fc8c3ab58.json index 3933b5e6a2..5d1ae61d0d 100644 --- a/backend/.sqlx/query-30f69fd4baef17716d26cc59bf6369d6768972478def50010f680103d7c4281b.json +++ b/backend/.sqlx/query-b7ecb69c99a1c840c400340c51e0a1b30410e587cf35d9488c5e5f4fc8c3ab58.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT value::text AS \"value!\", is_secret, description, value_valid_until\n FROM variable\n WHERE workspace_id = $1 AND path = $2", + "query": "SELECT value::text AS \"value!\", is_secret, description, value_valid_until, labels\n FROM variable\n WHERE workspace_id = $1 AND path = $2", "describe": { "columns": [ { @@ -22,6 +22,11 @@ "ordinal": 3, "name": "value_valid_until", "type_info": "Timestamptz" + }, + { + "ordinal": 4, + "name": "labels", + "type_info": "TextArray" } ], "parameters": { @@ -34,8 +39,9 @@ null, false, false, + true, true ] }, - "hash": "30f69fd4baef17716d26cc59bf6369d6768972478def50010f680103d7c4281b" + "hash": "b7ecb69c99a1c840c400340c51e0a1b30410e587cf35d9488c5e5f4fc8c3ab58" } diff --git a/backend/.sqlx/query-bcc9c9a09ecf260a9221037285e0f7d6892b8f91fee8db3563bffe87ab4ed889.json b/backend/.sqlx/query-bcc9c9a09ecf260a9221037285e0f7d6892b8f91fee8db3563bffe87ab4ed889.json new file mode 100644 index 0000000000..81f6a530cc --- /dev/null +++ b/backend/.sqlx/query-bcc9c9a09ecf260a9221037285e0f7d6892b8f91fee8db3563bffe87ab4ed889.json @@ -0,0 +1,88 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT owner, email, label, token_prefix, created_at, expiration, workspace_id,\n scopes, read_only, super_admin, admin, allowed_ips::text[] AS allowed_ips\n FROM token\n WHERE token_hash = $1 AND (expiration > NOW() OR expiration IS NULL)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "owner", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "label", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "token_prefix", + "type_info": "Varchar" + }, + { + "ordinal": 4, + "name": "created_at", + "type_info": "Timestamptz" + }, + { + "ordinal": 5, + "name": "expiration", + "type_info": "Timestamptz" + }, + { + "ordinal": 6, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 7, + "name": "scopes", + "type_info": "TextArray" + }, + { + "ordinal": 8, + "name": "read_only", + "type_info": "Bool" + }, + { + "ordinal": 9, + "name": "super_admin", + "type_info": "Bool" + }, + { + "ordinal": 10, + "name": "admin", + "type_info": "Bool" + }, + { + "ordinal": 11, + "name": "allowed_ips", + "type_info": "TextArray" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + true, + true, + true, + false, + false, + true, + true, + true, + false, + false, + false, + null + ] + }, + "hash": "bcc9c9a09ecf260a9221037285e0f7d6892b8f91fee8db3563bffe87ab4ed889" +} diff --git a/backend/.sqlx/query-be65c6653f4e116517ff14abb7e3f075a82e41f758daae9aeab4d558d781f817.json b/backend/.sqlx/query-be65c6653f4e116517ff14abb7e3f075a82e41f758daae9aeab4d558d781f817.json new file mode 100644 index 0000000000..18cf2c0f80 --- /dev/null +++ b/backend/.sqlx/query-be65c6653f4e116517ff14abb7e3f075a82e41f758daae9aeab4d558d781f817.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS(SELECT 1 FROM password WHERE totp_secret IS NOT NULL AND email <> $1)\n AS \"exists!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "be65c6653f4e116517ff14abb7e3f075a82e41f758daae9aeab4d558d781f817" +} diff --git a/backend/.sqlx/query-bf763c3ae4951537033d18ce48d3eb83d5c19e32aef199bf161e8ba8d1adf176.json b/backend/.sqlx/query-bf763c3ae4951537033d18ce48d3eb83d5c19e32aef199bf161e8ba8d1adf176.json deleted file mode 100644 index d6b261b56c..0000000000 --- a/backend/.sqlx/query-bf763c3ae4951537033d18ce48d3eb83d5c19e32aef199bf161e8ba8d1adf176.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO resource (workspace_id, path, value, description, resource_type, extra_perms, edited_at, created_by)\n SELECT $2, path,\n CASE WHEN $3::text IS NOT NULL AND resource_type = 'ai_agent'\n AND jsonb_typeof(value) = 'object' AND value ? 'on_behalf_of'\n THEN jsonb_set(value, '{on_behalf_of}', to_jsonb($3::text))\n ELSE value END,\n description, resource_type, extra_perms, edited_at, created_by\n FROM resource\n WHERE workspace_id = $1", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Text", - "Varchar", - "Text" - ] - }, - "nullable": [] - }, - "hash": "bf763c3ae4951537033d18ce48d3eb83d5c19e32aef199bf161e8ba8d1adf176" -} diff --git a/backend/.sqlx/query-c42f409f1c238ed5d6e9b57dd0b2a621e23dfbfefe99e848484b764fa57d837f.json b/backend/.sqlx/query-c42f409f1c238ed5d6e9b57dd0b2a621e23dfbfefe99e848484b764fa57d837f.json new file mode 100644 index 0000000000..7754fb84c2 --- /dev/null +++ b/backend/.sqlx/query-c42f409f1c238ed5d6e9b57dd0b2a621e23dfbfefe99e848484b764fa57d837f.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE password SET totp_recovery_codes = array_remove(totp_recovery_codes, $2)\n WHERE email = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "c42f409f1c238ed5d6e9b57dd0b2a621e23dfbfefe99e848484b764fa57d837f" +} diff --git a/backend/.sqlx/query-c901b1954818bfa402d2ded9f020c0862421001e10a5ac8cb3d1c1791b6ca597.json b/backend/.sqlx/query-c901b1954818bfa402d2ded9f020c0862421001e10a5ac8cb3d1c1791b6ca597.json new file mode 100644 index 0000000000..7ba9251dbe --- /dev/null +++ b/backend/.sqlx/query-c901b1954818bfa402d2ded9f020c0862421001e10a5ac8cb3d1c1791b6ca597.json @@ -0,0 +1,35 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT u.workspace_id, u.username,\n COALESCE(array_agg(g.group_) FILTER (WHERE g.group_ IS NOT NULL), '{}') AS \"groups!\"\n FROM usr u\n LEFT JOIN usr_to_group g ON g.workspace_id = u.workspace_id AND g.usr = u.username\n WHERE u.email = $1 AND NOT u.is_service_account\n AND EXISTS (SELECT 1 FROM workspace_protection_rule r\n WHERE r.workspace_id = u.workspace_id AND (r.rules & $2) <> 0)\n GROUP BY u.workspace_id, u.username", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "username", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "groups!", + "type_info": "VarcharArray" + } + ], + "parameters": { + "Left": [ + "Text", + "Int4" + ] + }, + "nullable": [ + false, + false, + null + ] + }, + "hash": "c901b1954818bfa402d2ded9f020c0862421001e10a5ac8cb3d1c1791b6ca597" +} diff --git a/backend/.sqlx/query-cc6a29cd0de33c439c5e966138fc38fb53dbdbc731fc4441049294ae10958881.json b/backend/.sqlx/query-cc6a29cd0de33c439c5e966138fc38fb53dbdbc731fc4441049294ae10958881.json new file mode 100644 index 0000000000..0a544fd174 --- /dev/null +++ b/backend/.sqlx/query-cc6a29cd0de33c439c5e966138fc38fb53dbdbc731fc4441049294ae10958881.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM token_expiry_notification WHERE token_hash = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "cc6a29cd0de33c439c5e966138fc38fb53dbdbc731fc4441049294ae10958881" +} diff --git a/backend/.sqlx/query-cde6d13d0a072e7910591335580434f0418b2ee23dc70e734568f820eec4b813.json b/backend/.sqlx/query-cde6d13d0a072e7910591335580434f0418b2ee23dc70e734568f820eec4b813.json deleted file mode 100644 index 6b564c60bb..0000000000 --- a/backend/.sqlx/query-cde6d13d0a072e7910591335580434f0418b2ee23dc70e734568f820eec4b813.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO raw_app (path, version, workspace_id, summary, edited_at, data, extra_perms)\n SELECT path, version, $2, summary, edited_at, data, extra_perms\n FROM raw_app\n WHERE workspace_id = $1", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Text", - "Varchar" - ] - }, - "nullable": [] - }, - "hash": "cde6d13d0a072e7910591335580434f0418b2ee23dc70e734568f820eec4b813" -} diff --git a/backend/.sqlx/query-cf027d3dcd4bd4c13ee012f549d2f3832660ad3ec1fcdacd418db3d793d0ce75.json b/backend/.sqlx/query-cf027d3dcd4bd4c13ee012f549d2f3832660ad3ec1fcdacd418db3d793d0ce75.json new file mode 100644 index 0000000000..9eae6a1f4d --- /dev/null +++ b/backend/.sqlx/query-cf027d3dcd4bd4c13ee012f549d2f3832660ad3ec1fcdacd418db3d793d0ce75.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE token SET super_admin = false WHERE email = $2 AND label != 'session' AND NOT $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Bool", + "Text" + ] + }, + "nullable": [] + }, + "hash": "cf027d3dcd4bd4c13ee012f549d2f3832660ad3ec1fcdacd418db3d793d0ce75" +} diff --git a/backend/.sqlx/query-d5dc35372cff3f14449b8ed95ac9691a7584c92e2b491f0c14b66f78dba24134.json b/backend/.sqlx/query-d5dc35372cff3f14449b8ed95ac9691a7584c92e2b491f0c14b66f78dba24134.json new file mode 100644 index 0000000000..10bf4a7f41 --- /dev/null +++ b/backend/.sqlx/query-d5dc35372cff3f14449b8ed95ac9691a7584c92e2b491f0c14b66f78dba24134.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO workspace_integrations\n (workspace_id, service_name, oauth_data, resource_path, created_by)\n VALUES ($1, $2, NULL, $3, $4)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + { + "Custom": { + "name": "native_trigger_service", + "kind": { + "Enum": [ + "nextcloud", + "google", + "github" + ] + } + } + }, + "Text", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "d5dc35372cff3f14449b8ed95ac9691a7584c92e2b491f0c14b66f78dba24134" +} diff --git a/backend/.sqlx/query-d5f86d08766c4dfee235b2a3c001b912ca690f498c1c3e2113d7b5bc9823c87d.json b/backend/.sqlx/query-d5f86d08766c4dfee235b2a3c001b912ca690f498c1c3e2113d7b5bc9823c87d.json new file mode 100644 index 0000000000..ee455947b1 --- /dev/null +++ b/backend/.sqlx/query-d5f86d08766c4dfee235b2a3c001b912ca690f498c1c3e2113d7b5bc9823c87d.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE password SET totp_secret = $2, totp_last_step = $3, totp_recovery_codes = $4\n WHERE email = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text", + "Int8", + "TextArray" + ] + }, + "nullable": [] + }, + "hash": "d5f86d08766c4dfee235b2a3c001b912ca690f498c1c3e2113d7b5bc9823c87d" +} diff --git a/backend/.sqlx/query-d63cd8c176f743a9e144c23912f3f91c128106e9a66ccedd3891bb884c622087.json b/backend/.sqlx/query-d63cd8c176f743a9e144c23912f3f91c128106e9a66ccedd3891bb884c622087.json new file mode 100644 index 0000000000..c5f940ea6c --- /dev/null +++ b/backend/.sqlx/query-d63cd8c176f743a9e144c23912f3f91c128106e9a66ccedd3891bb884c622087.json @@ -0,0 +1,59 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT v.path, r.created_by AS \"owner?\", true AS \"workspace!\", a.scopes AS \"scopes?\",\n NULL::text[] AS \"missing_scopes?\"\n FROM workspace_integrations wi\n JOIN variable v ON v.workspace_id = wi.workspace_id AND v.path = wi.resource_path\n JOIN resource r ON r.workspace_id = v.workspace_id AND r.path = v.path\n LEFT JOIN account a ON a.workspace_id = v.workspace_id AND a.id = v.account\n WHERE wi.workspace_id = $1 AND wi.service_name = $2 AND r.resource_type = $3", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "path", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "owner?", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "workspace!", + "type_info": "Bool" + }, + { + "ordinal": 3, + "name": "scopes?", + "type_info": "TextArray" + }, + { + "ordinal": 4, + "name": "missing_scopes?", + "type_info": "TextArray" + } + ], + "parameters": { + "Left": [ + "Text", + { + "Custom": { + "name": "native_trigger_service", + "kind": { + "Enum": [ + "nextcloud", + "google", + "github" + ] + } + } + }, + "Text" + ] + }, + "nullable": [ + false, + true, + null, + true, + null + ] + }, + "hash": "d63cd8c176f743a9e144c23912f3f91c128106e9a66ccedd3891bb884c622087" +} diff --git a/backend/.sqlx/query-d9c123e5d98464c456a4f8d421076f79c65e244aee086181b3dc65c2bf2fc4b2.json b/backend/.sqlx/query-d9c123e5d98464c456a4f8d421076f79c65e244aee086181b3dc65c2bf2fc4b2.json new file mode 100644 index 0000000000..acb0266e1b --- /dev/null +++ b/backend/.sqlx/query-d9c123e5d98464c456a4f8d421076f79c65e244aee086181b3dc65c2bf2fc4b2.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT name FROM folder WHERE workspace_id = $1 ORDER BY name", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "d9c123e5d98464c456a4f8d421076f79c65e244aee086181b3dc65c2bf2fc4b2" +} diff --git a/backend/.sqlx/query-be1de9116b18a40681cb8c5ec7578fd7c5f7ce77f7af63f766c2899d85fe0bef.json b/backend/.sqlx/query-dcf0071eb7adb1382ea183e0d92b4c7377ed7c40b81182f0b0ea95381b0f7b2e.json similarity index 63% rename from backend/.sqlx/query-be1de9116b18a40681cb8c5ec7578fd7c5f7ce77f7af63f766c2899d85fe0bef.json rename to backend/.sqlx/query-dcf0071eb7adb1382ea183e0d92b4c7377ed7c40b81182f0b0ea95381b0f7b2e.json index a03162fcb9..f4f212856b 100644 --- a/backend/.sqlx/query-be1de9116b18a40681cb8c5ec7578fd7c5f7ce77f7af63f766c2899d85fe0bef.json +++ b/backend/.sqlx/query-dcf0071eb7adb1382ea183e0d92b4c7377ed7c40b81182f0b0ea95381b0f7b2e.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT value FROM resource WHERE path = $1 AND workspace_id = $2", + "query": "SELECT value FROM resource WHERE path = $1 AND workspace_id = $2 FOR UPDATE", "describe": { "columns": [ { @@ -19,5 +19,5 @@ true ] }, - "hash": "be1de9116b18a40681cb8c5ec7578fd7c5f7ce77f7af63f766c2899d85fe0bef" + "hash": "dcf0071eb7adb1382ea183e0d92b4c7377ed7c40b81182f0b0ea95381b0f7b2e" } diff --git a/backend/.sqlx/query-df1fe2e7ef004b8de0e626f40fd737b3b4b662a89148cf6ac70eb3563ad7f0c5.json b/backend/.sqlx/query-df1fe2e7ef004b8de0e626f40fd737b3b4b662a89148cf6ac70eb3563ad7f0c5.json deleted file mode 100644 index 7f160dc856..0000000000 --- a/backend/.sqlx/query-df1fe2e7ef004b8de0e626f40fd737b3b4b662a89148cf6ac70eb3563ad7f0c5.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO flow (\n workspace_id, path, summary, description, value, edited_by, edited_at,\n archived, schema, extra_perms, dependency_job, tag,\n ws_error_handler_muted, dedicated_worker, timeout, visible_to_runner_only,\n concurrency_key, versions, on_behalf_of, on_behalf_of_email, lock_error_logs,\n job_token_scopes\n )\n SELECT $2, path, summary, description, value, edited_by, edited_at,\n archived, schema, extra_perms, NULL, tag,\n ws_error_handler_muted, dedicated_worker, timeout, visible_to_runner_only,\n concurrency_key, ARRAY[]::bigint[],\n -- Same predicate as clone_scripts.\n CASE WHEN on_behalf_of LIKE 'u/%' THEN\n (SELECT on_behalf_of WHERE EXISTS (\n SELECT 1 FROM usr u WHERE u.workspace_id = $2::varchar\n AND u.username = substring(on_behalf_of from 3)\n UNION ALL\n SELECT 1 FROM password p WHERE p.super_admin\n AND (p.username = substring(on_behalf_of from 3)\n OR p.email = substring(on_behalf_of from 3))))\n WHEN on_behalf_of LIKE 'g/%' THEN\n (SELECT on_behalf_of WHERE EXISTS (\n SELECT 1 FROM group_ g WHERE g.workspace_id = $2::varchar\n AND g.name = substring(on_behalf_of from 3)))\n ELSE\n (SELECT on_behalf_of WHERE EXISTS (\n SELECT 1 FROM usr u WHERE u.workspace_id = $2::varchar\n AND u.username = on_behalf_of\n UNION ALL\n SELECT 1 FROM password p WHERE p.email = on_behalf_of\n AND p.super_admin))\n END, on_behalf_of_email, lock_error_logs, job_token_scopes\n FROM flow\n WHERE workspace_id = $1", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Text", - "Varchar" - ] - }, - "nullable": [] - }, - "hash": "df1fe2e7ef004b8de0e626f40fd737b3b4b662a89148cf6ac70eb3563ad7f0c5" -} diff --git a/backend/.sqlx/query-e8148bcff949700670bec9c5a92f11aadf7ae32fdc943f28ece0261c9b2fe0e1.json b/backend/.sqlx/query-e8148bcff949700670bec9c5a92f11aadf7ae32fdc943f28ece0261c9b2fe0e1.json new file mode 100644 index 0000000000..2e6250b033 --- /dev/null +++ b/backend/.sqlx/query-e8148bcff949700670bec9c5a92f11aadf7ae32fdc943f28ece0261c9b2fe0e1.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT value::text AS \"value!\", account FROM variable\n WHERE path = $1 AND workspace_id = $2 FOR UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "value!", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "account", + "type_info": "Int4" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null, + true + ] + }, + "hash": "e8148bcff949700670bec9c5a92f11aadf7ae32fdc943f28ece0261c9b2fe0e1" +} diff --git a/backend/.sqlx/query-e9c732642ab0c3204fafb1486f871c6961ab78b262261ec1b9df4a6f276a7cd5.json b/backend/.sqlx/query-e9c732642ab0c3204fafb1486f871c6961ab78b262261ec1b9df4a6f276a7cd5.json new file mode 100644 index 0000000000..1e330057c1 --- /dev/null +++ b/backend/.sqlx/query-e9c732642ab0c3204fafb1486f871c6961ab78b262261ec1b9df4a6f276a7cd5.json @@ -0,0 +1,40 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT DISTINCT usage_kind::text AS \"usage_kind!\", usage_path, kind::text AS \"kind!\", path\n FROM asset\n WHERE workspace_id = $1 AND usage_kind IN ('script', 'flow')\n AND kind = 'resource'\n ORDER BY usage_path, path", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "usage_kind!", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "usage_path", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "kind!", + "type_info": "Text" + }, + { + "ordinal": 3, + "name": "path", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null, + false, + null, + false + ] + }, + "hash": "e9c732642ab0c3204fafb1486f871c6961ab78b262261ec1b9df4a6f276a7cd5" +} diff --git a/backend/.sqlx/query-eaac18f48398babf27a273da98eb9420b2c7fd5363525240b43b5c47928217f2.json b/backend/.sqlx/query-eaac18f48398babf27a273da98eb9420b2c7fd5363525240b43b5c47928217f2.json new file mode 100644 index 0000000000..4f805aa8fa --- /dev/null +++ b/backend/.sqlx/query-eaac18f48398babf27a273da98eb9420b2c7fd5363525240b43b5c47928217f2.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT totp_secret IS NOT NULL AS \"enabled!\" FROM password WHERE email = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "enabled!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "eaac18f48398babf27a273da98eb9420b2c7fd5363525240b43b5c47928217f2" +} diff --git a/backend/.sqlx/query-eaf0a5853b3550a4706d2aff6587b750ce7392ac6d7406403ce84127c5d978e3.json b/backend/.sqlx/query-eaf0a5853b3550a4706d2aff6587b750ce7392ac6d7406403ce84127c5d978e3.json new file mode 100644 index 0000000000..2ed99ef3d8 --- /dev/null +++ b/backend/.sqlx/query-eaf0a5853b3550a4706d2aff6587b750ce7392ac6d7406403ce84127c5d978e3.json @@ -0,0 +1,34 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT key, original_scheduled_for AS deferred_from, released_at FROM concurrency_key WHERE job_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "key", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "deferred_from", + "type_info": "Timestamptz" + }, + { + "ordinal": 2, + "name": "released_at", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + true, + true + ] + }, + "hash": "eaf0a5853b3550a4706d2aff6587b750ce7392ac6d7406403ce84127c5d978e3" +} diff --git a/backend/.sqlx/query-1553608e0d5a9a9b22c1a2c200bf02200df0007291133033f2b9013c2e508fe1.json b/backend/.sqlx/query-eb2a95b701e7149c6b459b4a745f70093d56a73efe44bae48ec5c7cb1f895e85.json similarity index 68% rename from backend/.sqlx/query-1553608e0d5a9a9b22c1a2c200bf02200df0007291133033f2b9013c2e508fe1.json rename to backend/.sqlx/query-eb2a95b701e7149c6b459b4a745f70093d56a73efe44bae48ec5c7cb1f895e85.json index 3e4b85a916..81650db09f 100644 --- a/backend/.sqlx/query-1553608e0d5a9a9b22c1a2c200bf02200df0007291133033f2b9013c2e508fe1.json +++ b/backend/.sqlx/query-eb2a95b701e7149c6b459b4a745f70093d56a73efe44bae48ec5c7cb1f895e85.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO token\n (token_hash, token_prefix, token, email, label, expiration, super_admin, scopes, workspace_id)\n VALUES ($1, $2, $3, $4, $5, now() + ($6 || ' seconds')::interval, false, $7, $8)", + "query": "INSERT INTO token\n (token_hash, token_prefix, token, email, label, expiration, super_admin, scopes, workspace_id, admin)\n VALUES ($1, $2, $3, $4, $5, now() + ($6 || ' seconds')::interval, false, $7, $8, false)", "describe": { "columns": [], "parameters": { @@ -17,5 +17,5 @@ }, "nullable": [] }, - "hash": "1553608e0d5a9a9b22c1a2c200bf02200df0007291133033f2b9013c2e508fe1" + "hash": "eb2a95b701e7149c6b459b4a745f70093d56a73efe44bae48ec5c7cb1f895e85" } diff --git a/backend/.sqlx/query-ed4c95dbac85508ab9836f380a550ba3dd46e63cec97c789bd0c06b81fc92a59.json b/backend/.sqlx/query-ed4c95dbac85508ab9836f380a550ba3dd46e63cec97c789bd0c06b81fc92a59.json new file mode 100644 index 0000000000..92361f1f50 --- /dev/null +++ b/backend/.sqlx/query-ed4c95dbac85508ab9836f380a550ba3dd46e63cec97c789bd0c06b81fc92a59.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE password SET totp_last_step = $2 WHERE email = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "ed4c95dbac85508ab9836f380a550ba3dd46e63cec97c789bd0c06b81fc92a59" +} diff --git a/backend/.sqlx/query-ef655ad80f51c7b5ac50090db46c96e9143a2867c8ac50e6dd8937e24fefb38e.json b/backend/.sqlx/query-ef655ad80f51c7b5ac50090db46c96e9143a2867c8ac50e6dd8937e24fefb38e.json new file mode 100644 index 0000000000..3f28206036 --- /dev/null +++ b/backend/.sqlx/query-ef655ad80f51c7b5ac50090db46c96e9143a2867c8ac50e6dd8937e24fefb38e.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE token SET scopes = $1 WHERE token_hash = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "TextArray", + "Text" + ] + }, + "nullable": [] + }, + "hash": "ef655ad80f51c7b5ac50090db46c96e9143a2867c8ac50e6dd8937e24fefb38e" +} diff --git a/backend/.sqlx/query-f17979f68f56cb784a4fb0cc5fc4da971b6a617a5c67338dd06e98f0a065d468.json b/backend/.sqlx/query-f17979f68f56cb784a4fb0cc5fc4da971b6a617a5c67338dd06e98f0a065d468.json deleted file mode 100644 index 819a8e73b7..0000000000 --- a/backend/.sqlx/query-f17979f68f56cb784a4fb0cc5fc4da971b6a617a5c67338dd06e98f0a065d468.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO token (token_hash, token_prefix, token, email, label, expiration, scopes, workspace_id, super_admin)\n SELECT $1::varchar, $2::varchar, $3::varchar, $4::varchar, $5::varchar, now() + ($6 || ' seconds')::interval, $7::text[], $8::varchar,\n $9::bool AND COALESCE((SELECT super_admin FROM password WHERE email = $4), false)\n WHERE NOT EXISTS(SELECT 1 FROM workspace WHERE id = $8 AND deleted = true)", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Varchar", - "Varchar", - "Varchar", - "Varchar", - "Varchar", - "Text", - "TextArray", - "Varchar", - "Bool" - ] - }, - "nullable": [] - }, - "hash": "f17979f68f56cb784a4fb0cc5fc4da971b6a617a5c67338dd06e98f0a065d468" -} diff --git a/backend/.sqlx/query-f2d208bcb735dcc3c24c8e09b5720037162032a79fc54a03652322a1543161a5.json b/backend/.sqlx/query-f2d208bcb735dcc3c24c8e09b5720037162032a79fc54a03652322a1543161a5.json new file mode 100644 index 0000000000..7189e6e50d --- /dev/null +++ b/backend/.sqlx/query-f2d208bcb735dcc3c24c8e09b5720037162032a79fc54a03652322a1543161a5.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO raw_app (path, version, workspace_id, summary, edited_at, data, extra_perms, labels)\n SELECT path, version, $2, summary, edited_at, data, extra_perms, labels\n FROM raw_app\n WHERE workspace_id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "f2d208bcb735dcc3c24c8e09b5720037162032a79fc54a03652322a1543161a5" +} diff --git a/backend/.sqlx/query-dc6ffc9946325e794f3a9d1cf621a9c07d211351195c399f6ff25c1dc7adb01a.json b/backend/.sqlx/query-f4389161e4c6d6379c57fd1cd8c6fa9360f4c7ee5608be2fd7b26f0e04878278.json similarity index 64% rename from backend/.sqlx/query-dc6ffc9946325e794f3a9d1cf621a9c07d211351195c399f6ff25c1dc7adb01a.json rename to backend/.sqlx/query-f4389161e4c6d6379c57fd1cd8c6fa9360f4c7ee5608be2fd7b26f0e04878278.json index 51a178a3e3..f62943f289 100644 --- a/backend/.sqlx/query-dc6ffc9946325e794f3a9d1cf621a9c07d211351195c399f6ff25c1dc7adb01a.json +++ b/backend/.sqlx/query-f4389161e4c6d6379c57fd1cd8c6fa9360f4c7ee5608be2fd7b26f0e04878278.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT value, summary, description, schema\n FROM flow\n WHERE workspace_id = $1 AND path = $2 AND archived = false", + "query": "SELECT value, summary, description, schema, labels\n FROM flow\n WHERE workspace_id = $1 AND path = $2 AND archived = false", "describe": { "columns": [ { @@ -22,6 +22,11 @@ "ordinal": 3, "name": "schema", "type_info": "Json" + }, + { + "ordinal": 4, + "name": "labels", + "type_info": "TextArray" } ], "parameters": { @@ -34,8 +39,9 @@ false, false, false, + true, true ] }, - "hash": "dc6ffc9946325e794f3a9d1cf621a9c07d211351195c399f6ff25c1dc7adb01a" + "hash": "f4389161e4c6d6379c57fd1cd8c6fa9360f4c7ee5608be2fd7b26f0e04878278" } diff --git a/backend/.sqlx/query-f4ad11395351f78b603ee5aab3b20eca2960c29af676f78c16847e4a0a6fc199.json b/backend/.sqlx/query-f4ad11395351f78b603ee5aab3b20eca2960c29af676f78c16847e4a0a6fc199.json new file mode 100644 index 0000000000..918eaa0679 --- /dev/null +++ b/backend/.sqlx/query-f4ad11395351f78b603ee5aab3b20eca2960c29af676f78c16847e4a0a6fc199.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE variable v SET account = NULL FROM variable o\n WHERE o.workspace_id = v.workspace_id AND o.path = v.path\n AND v.workspace_id = $1 AND v.path = $2 AND v.account IS NOT NULL\n RETURNING o.account", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "account", + "type_info": "Int4" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + true + ] + }, + "hash": "f4ad11395351f78b603ee5aab3b20eca2960c29af676f78c16847e4a0a6fc199" +} diff --git a/backend/.sqlx/query-f91ff955e25f6d241208449ef7656fd3fa330926f0b463c1ab50b740268e2326.json b/backend/.sqlx/query-f91ff955e25f6d241208449ef7656fd3fa330926f0b463c1ab50b740268e2326.json new file mode 100644 index 0000000000..2e67e2cf47 --- /dev/null +++ b/backend/.sqlx/query-f91ff955e25f6d241208449ef7656fd3fa330926f0b463c1ab50b740268e2326.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO token (token_hash, token_prefix, token, email, label, expiration, scopes, workspace_id, super_admin, admin)\n SELECT $1::varchar, $2::varchar, $3::varchar, $4::varchar, $5::varchar, now() + ($6 || ' seconds')::interval, $7::text[], $8::varchar,\n $9::bool AND COALESCE((SELECT super_admin FROM password WHERE email = $4), false), true\n WHERE NOT EXISTS(SELECT 1 FROM workspace WHERE id = $8 AND deleted = true)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Text", + "TextArray", + "Varchar", + "Bool" + ] + }, + "nullable": [] + }, + "hash": "f91ff955e25f6d241208449ef7656fd3fa330926f0b463c1ab50b740268e2326" +} diff --git a/backend/.sqlx/query-ccc49a2a6e11f874825365de758bdc0e1934d67d3f2b14047d434b77d370af21.json b/backend/.sqlx/query-fa63f242325c469969b2510b4d3a25e412a492bf3ce96db595bd7d6347981477.json similarity index 53% rename from backend/.sqlx/query-ccc49a2a6e11f874825365de758bdc0e1934d67d3f2b14047d434b77d370af21.json rename to backend/.sqlx/query-fa63f242325c469969b2510b4d3a25e412a492bf3ce96db595bd7d6347981477.json index a9348dfa8b..342d34826d 100644 --- a/backend/.sqlx/query-ccc49a2a6e11f874825365de758bdc0e1934d67d3f2b14047d434b77d370af21.json +++ b/backend/.sqlx/query-fa63f242325c469969b2510b4d3a25e412a492bf3ce96db595bd7d6347981477.json @@ -1,16 +1,17 @@ { "db_name": "PostgreSQL", - "query": "SELECT super_admin FROM password WHERE email = $1 AND disabled = false", + "query": "SELECT is_admin FROM usr WHERE workspace_id = $1 AND email = $2 AND NOT disabled", "describe": { "columns": [ { "ordinal": 0, - "name": "super_admin", + "name": "is_admin", "type_info": "Bool" } ], "parameters": { "Left": [ + "Text", "Text" ] }, @@ -18,5 +19,5 @@ false ] }, - "hash": "ccc49a2a6e11f874825365de758bdc0e1934d67d3f2b14047d434b77d370af21" + "hash": "fa63f242325c469969b2510b4d3a25e412a492bf3ce96db595bd7d6347981477" } diff --git a/backend/.sqlx/query-aed606f8c8d91a924ac457b4eabdf391947d5fc3da90ef98a7b793c2430eb7bc.json b/backend/.sqlx/query-fd6afd1480c22e9911b50b2b74daca5c21841ea4e86243a82461e3c9e359a316.json similarity index 78% rename from backend/.sqlx/query-aed606f8c8d91a924ac457b4eabdf391947d5fc3da90ef98a7b793c2430eb7bc.json rename to backend/.sqlx/query-fd6afd1480c22e9911b50b2b74daca5c21841ea4e86243a82461e3c9e359a316.json index 0bd5d0eca5..b00f6cb0a4 100644 --- a/backend/.sqlx/query-aed606f8c8d91a924ac457b4eabdf391947d5fc3da90ef98a7b793c2430eb7bc.json +++ b/backend/.sqlx/query-fd6afd1480c22e9911b50b2b74daca5c21841ea4e86243a82461e3c9e359a316.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT q.id AS \"id!\", j.created_by, j.permissioned_as, j.permissioned_as_email, j.trigger, j.trigger_kind AS \"trigger_kind: TriggerKindLabel\", j.preprocessed, j.args AS \"args: sqlx::types::Json>>\", p.job_token_scopes AS \"job_token_scopes?\" FROM v2_job_queue q JOIN v2_job j USING (id) JOIN script s ON s.workspace_id = j.workspace_id AND s.hash = j.runnable_id LEFT JOIN job_perms p ON p.job_id = q.id WHERE j.workspace_id = $1 AND j.runnable_path = $2 AND j.kind = 'script' AND j.flow_step_id IS NULL AND j.runnable_id != $3 AND q.canceled_by IS NULL AND s.restart_unless_cancelled", + "query": "SELECT q.id AS \"id!\", j.created_by, j.permissioned_as, j.permissioned_as_email, j.trigger, j.trigger_kind AS \"trigger_kind: TriggerKindLabel\", j.preprocessed, j.args AS \"args: sqlx::types::Json>>\", p.job_token_scopes AS \"job_token_scopes?\", s.on_behalf_of AS version_on_behalf_of FROM v2_job_queue q JOIN v2_job j USING (id) JOIN script s ON s.workspace_id = j.workspace_id AND s.hash = j.runnable_id LEFT JOIN job_perms p ON p.job_id = q.id WHERE j.workspace_id = $1 AND j.runnable_path = $2 AND j.kind = 'script' AND j.flow_step_id IS NULL AND j.runnable_id != $3 AND q.canceled_by IS NULL AND s.restart_unless_cancelled", "describe": { "columns": [ { @@ -76,6 +76,11 @@ "ordinal": 8, "name": "job_token_scopes?", "type_info": "TextArray" + }, + { + "ordinal": 9, + "name": "version_on_behalf_of", + "type_info": "Varchar" } ], "parameters": { @@ -94,8 +99,9 @@ true, true, true, + true, true ] }, - "hash": "aed606f8c8d91a924ac457b4eabdf391947d5fc3da90ef98a7b793c2430eb7bc" + "hash": "fd6afd1480c22e9911b50b2b74daca5c21841ea4e86243a82461e3c9e359a316" } diff --git a/backend/.sqlx/query-fffeda2be11d5c6d5969d49569d726046f138262c097e6f05a70bdea35e2038a.json b/backend/.sqlx/query-fffeda2be11d5c6d5969d49569d726046f138262c097e6f05a70bdea35e2038a.json new file mode 100644 index 0000000000..83e6269d09 --- /dev/null +++ b/backend/.sqlx/query-fffeda2be11d5c6d5969d49569d726046f138262c097e6f05a70bdea35e2038a.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE password SET totp_secret = $2, totp_pending_secret = $3 WHERE email = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "fffeda2be11d5c6d5969d49569d726046f138262c097e6f05a70bdea35e2038a" +} diff --git a/backend/Cargo.lock b/backend/Cargo.lock index c01150d464..93b8caccba 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -77,9 +77,9 @@ dependencies = [ [[package]] name = "ahash" -version = "0.8.13" +version = "0.8.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fca89247609239eeb6915e6991111866b92d7b31025e69302bbf430cc4d2c38" +checksum = "3019c0b8d883a8a17df3129e417ef463c087807d245e8881a31d583dee1c0519" dependencies = [ "cfg-if", "const-random", @@ -116,9 +116,9 @@ dependencies = [ [[package]] name = "allocator-api2" -version = "0.2.21" +version = "0.2.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" +checksum = "57b212daf2e827b1ccdd778b7eb48ba433e58cb0e4f27b43cd6b7a608425a014" [[package]] name = "amq-protocol" @@ -280,9 +280,9 @@ checksum = "3d62b7694a562cdf5a74227903507c56ab2cc8bdd1f781ed5cb4cf9c9f810bfc" [[package]] name = "arrayvec" -version = "0.7.8" +version = "0.7.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" +checksum = "47a64a0fd06e123e9e3cf3ad01432af17dcab8185e8023edcf184fe696f9675d" [[package]] name = "arrow" @@ -325,7 +325,7 @@ version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70732f04d285d49054a48b72c54f791bb3424abae92d27aafdf776c98af161c8" dependencies = [ - "ahash 0.8.13", + "ahash 0.8.15", "arrow-buffer", "arrow-data", "arrow-schema", @@ -469,7 +469,7 @@ version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd2b45757d6a2373faa3352d02ff5b54b098f5e21dccebc45a21806bc34501e5" dependencies = [ - "ahash 0.8.13", + "ahash 0.8.15", "arrow-array", "arrow-buffer", "arrow-data", @@ -1870,14 +1870,14 @@ dependencies = [ [[package]] name = "blake3" -version = "1.8.7" +version = "1.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +checksum = "68fe79e887dd9b3d00ffb29973ff39df3d99b81e6fefbde49636989bd56264d6" dependencies = [ "arrayvec", "cc", "cfg-if", - "constant_time_eq 0.4.2", + "constant_time_eq 0.6.2", "cpufeatures 0.3.1", ] @@ -2367,9 +2367,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.11.3" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" dependencies = [ "find-msvc-tools", "jobserver", @@ -2646,12 +2646,12 @@ dependencies = [ [[package]] name = "const-hex" -version = "1.19.3" +version = "1.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e59eef12462b0f9b0a3620219be5d639afd79fe39dff0a42c3997061f9298b4" +checksum = "dec64a10a1f3012c9950a1759c99e09444a61087441a9b1ced0039c21365f859" dependencies = [ "cfg-if", - "cpufeatures 0.2.17", + "cpufeatures 0.3.1", "proptest", "serde_core", ] @@ -2722,9 +2722,12 @@ checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6" [[package]] name = "constant_time_eq" -version = "0.4.2" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" +checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7" +dependencies = [ + "rustversion", +] [[package]] name = "convert_case" @@ -3096,9 +3099,9 @@ dependencies = [ [[package]] name = "curve25519-dalek" -version = "5.0.0" +version = "5.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23" +checksum = "94c1aa5a9b7626ed65ac0cf5ea9d4f1547af89017fbac20bd4de40022fff516f" dependencies = [ "cfg-if", "cpufeatures 0.3.1", @@ -3430,7 +3433,7 @@ version = "47.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0734015d81c8375eb5d4869b7f7ecccc2ee8d6cb81948ef737cd0e7b743bd69c" dependencies = [ - "ahash 0.8.13", + "ahash 0.8.15", "arrow", "arrow-ipc", "base64 0.22.1", @@ -3670,7 +3673,7 @@ version = "47.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "408a05dafdc70d05a38a29005b8b15e21b0238734dab1e98483fcb58038c5aba" dependencies = [ - "ahash 0.8.13", + "ahash 0.8.15", "arrow", "datafusion-common", "datafusion-doc", @@ -3691,7 +3694,7 @@ version = "47.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "756d21da2dd6c9bef97af1504970ff56cbf35d03fbd4ffd62827f02f4d2279d4" dependencies = [ - "ahash 0.8.13", + "ahash 0.8.15", "arrow", "datafusion-common", "datafusion-expr-common", @@ -3798,7 +3801,7 @@ version = "47.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "64c536062b0076f4e30084065d805f389f9fe38af0ca75bcbac86bc5e9fbab65" dependencies = [ - "ahash 0.8.13", + "ahash 0.8.15", "arrow", "datafusion-common", "datafusion-expr", @@ -3820,7 +3823,7 @@ version = "47.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8a92b53b3193fac1916a1c5b8e3f4347c526f6822e56b71faa5fb372327a863" dependencies = [ - "ahash 0.8.13", + "ahash 0.8.15", "arrow", "datafusion-common", "datafusion-expr-common", @@ -3853,7 +3856,7 @@ version = "47.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "690c615db468c2e5fe5085b232d8b1c088299a6c63d87fd960a354a71f7acb55" dependencies = [ - "ahash 0.8.13", + "ahash 0.8.15", "arrow", "arrow-ord", "arrow-schema", @@ -4850,7 +4853,7 @@ dependencies = [ "libc", "option-ext", "redox_users 0.5.3", - "windows-sys 0.61.2", + "windows-sys 0.101.0", ] [[package]] @@ -5070,10 +5073,10 @@ version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de" dependencies = [ - "curve25519-dalek 5.0.0", + "curve25519-dalek 5.1.0", "ed25519 3.0.0", "serde", - "sha2 0.11.1", + "sha2 0.11.3", "signature 3.0.0", "subtle", "zeroize", @@ -5442,9 +5445,9 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.15" +version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" [[package]] name = "fips203" @@ -5897,14 +5900,12 @@ dependencies = [ [[package]] name = "generator" -version = "0.8.12" +version = "0.8.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea6c6a73cd1aa4f4f00c02b109fa55d3a9d6ecc2fc4f53177b74ed6ee23b0c53" +checksum = "66831419d9074e766421508dff218bf79d99616bc5e56e34599d3b433714a4a4" dependencies = [ - "cc", "libc", "log", - "rustversion", "windows-core 0.100.0", "windows-sys 0.61.2", ] @@ -6292,7 +6293,7 @@ version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" dependencies = [ - "ahash 0.8.13", + "ahash 0.8.15", "allocator-api2", ] @@ -7176,9 +7177,9 @@ dependencies = [ [[package]] name = "ipnet" -version = "2.12.2" +version = "2.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +checksum = "007d6e6b91097094791302ccc6cd0588e0700ddac5c6829035bcd71eff4dc433" [[package]] name = "is-macro" @@ -7659,7 +7660,7 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f1326e946fadf6248febdf8a1c001809c3899ccf48cb9768cbc536b741040dc" dependencies = [ - "ahash 0.8.13", + "ahash 0.8.15", "async-broadcast", "async-stream", "backon", @@ -9417,9 +9418,9 @@ dependencies = [ [[package]] name = "owo-colors" -version = "4.4.0" +version = "4.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c45bb4a6ae1280ec0803b1ef9d3455eb50f01efbbe1447ab020f1d54fba9d8" +checksum = "87951d615e539b79093477ecd12fd25e8870d41a7f842dfb76bbda747f971117" [[package]] name = "p12-keystore" @@ -9465,7 +9466,7 @@ dependencies = [ "elliptic-curve 0.14.3", "primefield", "primeorder 0.14.0", - "sha2 0.11.1", + "sha2 0.11.3", ] [[package]] @@ -9491,7 +9492,7 @@ dependencies = [ "fiat-crypto 0.3.0", "primefield", "primeorder 0.14.0", - "sha2 0.11.1", + "sha2 0.11.3", ] [[package]] @@ -9552,7 +9553,7 @@ version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b17da4150748086bd43352bc77372efa9b6e3dbd06a04831d2a98c041c225cfa" dependencies = [ - "ahash 0.8.13", + "ahash 0.8.15", "arrow-array", "arrow-buffer", "arrow-cast", @@ -10101,7 +10102,7 @@ dependencies = [ "md-5 0.11.0", "memchr", "rand 0.10.4", - "sha2 0.11.1", + "sha2 0.11.3", "stringprep", ] @@ -10215,7 +10216,7 @@ version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "toml_edit 0.25.20+spec-1.1.0", + "toml_edit 0.25.21+spec-1.1.0", ] [[package]] @@ -10823,9 +10824,9 @@ dependencies = [ [[package]] name = "rdkafka-sys" -version = "4.11.0+2.16.0" +version = "4.11.1+2.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3d6665101ead1a55f2fc23e66df201c5ab60cd52718a73af266155ac59f43c2" +checksum = "88df612f0d688c1fe3a7926af3a5efbf53b9dc9f95843bb9acdeda0e9a868616" dependencies = [ "cmake", "curl-sys", @@ -10976,9 +10977,9 @@ checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" [[package]] name = "relative-path" -version = "2.0.3" +version = "2.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38540a682c6e9bca04a8bca9e5ec5a6ba168dfbb04c9998fe517a9befb92eb68" +checksum = "860463dbb4c1d8d2df5b9938771d671ec6f30a8acea945add969ad74987b2ff0" dependencies = [ "serde_core", ] @@ -11261,9 +11262,9 @@ dependencies = [ [[package]] name = "rmcp-macros" -version = "3.11.0" +version = "3.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3598e3f36f4af2b5219b133baf7d97a2197039225adc3d4acf3dd8805b5a2aef" +checksum = "43c1bf063ba32333267a8bc282ec33ae0edf56bf74890118cb0c7bf910a7a1c0" dependencies = [ "darling 0.24.1", "proc-macro2", @@ -12392,9 +12393,9 @@ dependencies = [ [[package]] name = "sha2" -version = "0.11.1" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c" dependencies = [ "cfg-if", "cpufeatures 0.3.1", @@ -12771,7 +12772,7 @@ dependencies = [ [[package]] name = "sqlx" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" +source = "git+https://github.com/windmill-labs/sqlx?rev=ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459#ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" dependencies = [ "sqlx-core", "sqlx-macros", @@ -12783,7 +12784,7 @@ dependencies = [ [[package]] name = "sqlx-core" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" +source = "git+https://github.com/windmill-labs/sqlx?rev=ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459#ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" dependencies = [ "base64 0.22.1", "bigdecimal", @@ -12821,7 +12822,7 @@ dependencies = [ [[package]] name = "sqlx-macros" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" +source = "git+https://github.com/windmill-labs/sqlx?rev=ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459#ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" dependencies = [ "proc-macro2", "quote", @@ -12833,7 +12834,7 @@ dependencies = [ [[package]] name = "sqlx-macros-core" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" +source = "git+https://github.com/windmill-labs/sqlx?rev=ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459#ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" dependencies = [ "dotenvy", "either", @@ -12857,7 +12858,7 @@ dependencies = [ [[package]] name = "sqlx-mysql" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" +source = "git+https://github.com/windmill-labs/sqlx?rev=ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459#ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" dependencies = [ "atoi", "base64 0.22.1", @@ -12901,7 +12902,7 @@ dependencies = [ [[package]] name = "sqlx-postgres" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" +source = "git+https://github.com/windmill-labs/sqlx?rev=ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459#ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" dependencies = [ "atoi", "base64 0.22.1", @@ -12941,7 +12942,7 @@ dependencies = [ [[package]] name = "sqlx-sqlite" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" +source = "git+https://github.com/windmill-labs/sqlx?rev=ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459#ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" dependencies = [ "atoi", "chrono", @@ -14482,9 +14483,9 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.25.20+spec-1.1.0" +version = "0.25.21+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e76360e201d6dbd6583e17795ba71a88f47365a9139c8450a7979c32303b8e73" +checksum = "88497dab46de5bf343ec66b05c251e48c6213f3e9170c70a70a823f7abe886a4" dependencies = [ "indexmap 2.14.2", "toml_datetime 1.1.3+spec-1.1.0", @@ -14494,9 +14495,9 @@ dependencies = [ [[package]] name = "toml_parser" -version = "1.1.6+spec-1.1.0" +version = "1.1.7+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31" +checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a" dependencies = [ "winnow 1.0.5", ] @@ -15654,7 +15655,7 @@ dependencies = [ [[package]] name = "windmill" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-nats", @@ -15744,7 +15745,7 @@ dependencies = [ [[package]] name = "windmill-ai" -version = "1.884.1" +version = "1.894.1" dependencies = [ "async-stream", "async-trait", @@ -15779,7 +15780,7 @@ dependencies = [ [[package]] name = "windmill-alerting" -version = "1.884.1" +version = "1.894.1" dependencies = [ "axum", "chrono", @@ -15792,7 +15793,7 @@ dependencies = [ [[package]] name = "windmill-api" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "argon2", @@ -15934,7 +15935,7 @@ dependencies = [ [[package]] name = "windmill-api-agent-workers" -version = "1.884.1" +version = "1.894.1" dependencies = [ "axum", "chrono", @@ -15958,7 +15959,7 @@ dependencies = [ [[package]] name = "windmill-api-assets" -version = "1.884.1" +version = "1.894.1" dependencies = [ "axum", "chrono", @@ -15975,7 +15976,7 @@ dependencies = [ [[package]] name = "windmill-api-auth" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "axum", @@ -15994,6 +15995,7 @@ dependencies = [ "tokio", "tower-cookies", "tracing", + "url", "uuid", "windmill-audit", "windmill-common", @@ -16002,7 +16004,7 @@ dependencies = [ [[package]] name = "windmill-api-client" -version = "1.884.1" +version = "1.894.1" dependencies = [ "reqwest 0.12.28", "serde", @@ -16012,7 +16014,7 @@ dependencies = [ [[package]] name = "windmill-api-configs" -version = "1.884.1" +version = "1.894.1" dependencies = [ "axum", "chrono", @@ -16029,7 +16031,7 @@ dependencies = [ [[package]] name = "windmill-api-debug" -version = "1.884.1" +version = "1.894.1" dependencies = [ "axum", "base64 0.22.1", @@ -16051,7 +16053,7 @@ dependencies = [ [[package]] name = "windmill-api-embeddings" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "axum", @@ -16074,7 +16076,7 @@ dependencies = [ [[package]] name = "windmill-api-flow-conversations" -version = "1.884.1" +version = "1.894.1" dependencies = [ "axum", "chrono", @@ -16090,7 +16092,7 @@ dependencies = [ [[package]] name = "windmill-api-flows" -version = "1.884.1" +version = "1.894.1" dependencies = [ "axum", "chrono", @@ -16112,7 +16114,7 @@ dependencies = [ [[package]] name = "windmill-api-groups" -version = "1.884.1" +version = "1.894.1" dependencies = [ "axum", "chrono", @@ -16134,7 +16136,7 @@ dependencies = [ [[package]] name = "windmill-api-inputs" -version = "1.884.1" +version = "1.894.1" dependencies = [ "axum", "chrono", @@ -16148,7 +16150,7 @@ dependencies = [ [[package]] name = "windmill-api-integration-tests" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-nats", @@ -16184,7 +16186,7 @@ dependencies = [ [[package]] name = "windmill-api-jobs" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "axum", @@ -16210,7 +16212,7 @@ dependencies = [ [[package]] name = "windmill-api-npm-proxy" -version = "1.884.1" +version = "1.894.1" dependencies = [ "axum", "chrono", @@ -16238,7 +16240,7 @@ dependencies = [ [[package]] name = "windmill-api-openapi" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "axum", @@ -16260,7 +16262,7 @@ dependencies = [ [[package]] name = "windmill-api-schedule" -version = "1.884.1" +version = "1.894.1" dependencies = [ "axum", "chrono", @@ -16279,7 +16281,7 @@ dependencies = [ [[package]] name = "windmill-api-scripts" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "axum", @@ -16321,7 +16323,7 @@ dependencies = [ [[package]] name = "windmill-api-settings" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "axum", @@ -16352,7 +16354,7 @@ dependencies = [ [[package]] name = "windmill-api-sse" -version = "1.884.1" +version = "1.894.1" dependencies = [ "lazy_static", "serde", @@ -16364,16 +16366,20 @@ dependencies = [ [[package]] name = "windmill-api-users" -version = "1.884.1" +version = "1.894.1" dependencies = [ "argon2", "axum", + "base32", "chrono", + "hmac 0.12.1", "http 1.5.0", "hyper 1.13.0", "lazy_static", + "rand 0.9.5", "serde", "serde_json", + "sha1", "sqlx", "time", "tokio", @@ -16388,7 +16394,7 @@ dependencies = [ [[package]] name = "windmill-api-workers" -version = "1.884.1" +version = "1.894.1" dependencies = [ "axum", "chrono", @@ -16403,7 +16409,7 @@ dependencies = [ [[package]] name = "windmill-api-workspaces" -version = "1.884.1" +version = "1.894.1" dependencies = [ "axum", "chrono", @@ -16442,7 +16448,7 @@ dependencies = [ [[package]] name = "windmill-audit" -version = "1.884.1" +version = "1.894.1" dependencies = [ "chrono", "lazy_static", @@ -16457,7 +16463,7 @@ dependencies = [ [[package]] name = "windmill-autoscaling" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "axum", @@ -16476,7 +16482,7 @@ dependencies = [ [[package]] name = "windmill-common" -version = "1.884.1" +version = "1.894.1" dependencies = [ "aes-gcm", "aho-corasick", @@ -16530,6 +16536,7 @@ dependencies = [ "openidconnect", "opentelemetry 0.30.0", "opentelemetry-appender-tracing", + "opentelemetry-http 0.30.0", "opentelemetry-otlp 0.30.0", "opentelemetry-semantic-conventions 0.30.0", "opentelemetry_sdk 0.30.0", @@ -16545,6 +16552,7 @@ dependencies = [ "rand 0.9.5", "rcgen", "regex", + "reqwest 0.12.28", "reqwest 0.13.5", "reqwest-middleware", "reqwest-retry", @@ -16595,7 +16603,7 @@ dependencies = [ [[package]] name = "windmill-dep-map" -version = "1.884.1" +version = "1.894.1" dependencies = [ "chrono", "futures", @@ -16615,7 +16623,7 @@ dependencies = [ [[package]] name = "windmill-git-sync" -version = "1.884.1" +version = "1.894.1" dependencies = [ "regex", "serde", @@ -16632,7 +16640,7 @@ dependencies = [ [[package]] name = "windmill-indexer" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "astral-tokio-tar", @@ -16659,7 +16667,7 @@ dependencies = [ [[package]] name = "windmill-jseval" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "futures", @@ -16676,7 +16684,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.884.1" +version = "1.894.1" dependencies = [ "itertools 0.14.0", "lazy_static", @@ -16692,7 +16700,7 @@ dependencies = [ [[package]] name = "windmill-mcp" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-trait", @@ -16714,7 +16722,7 @@ dependencies = [ [[package]] name = "windmill-native-triggers" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-trait", @@ -16746,7 +16754,7 @@ dependencies = [ [[package]] name = "windmill-oauth" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "arc-swap", @@ -16771,7 +16779,7 @@ dependencies = [ [[package]] name = "windmill-object-store" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-stream", @@ -16807,7 +16815,7 @@ dependencies = [ [[package]] name = "windmill-operator" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "futures", @@ -16826,7 +16834,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.884.1" +version = "1.894.1" dependencies = [ "convert_case 0.6.0", "serde", @@ -16835,7 +16843,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "lazy_static", @@ -16847,7 +16855,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "serde_json", @@ -16859,7 +16867,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "gosyn", @@ -16871,7 +16879,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "lazy_static", @@ -16883,7 +16891,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "serde_json", @@ -16895,7 +16903,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "nu-parser", @@ -16906,7 +16914,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16917,7 +16925,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16929,7 +16937,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "ruff_python_ast", @@ -16940,7 +16948,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-recursion", @@ -16963,7 +16971,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "serde_json", @@ -16975,7 +16983,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "lazy_static", @@ -16989,7 +16997,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -17006,7 +17014,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "lazy_static", @@ -17019,7 +17027,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "serde", @@ -17031,7 +17039,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "lazy_static", @@ -17049,7 +17057,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -17065,7 +17073,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "ruff_python_ast", @@ -17082,7 +17090,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "lazy_static", @@ -17096,7 +17104,7 @@ dependencies = [ [[package]] name = "windmill-queue" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-recursion", @@ -17134,7 +17142,7 @@ dependencies = [ [[package]] name = "windmill-runtime-nativets" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "const_format", @@ -17172,7 +17180,7 @@ dependencies = [ [[package]] name = "windmill-sql-datatype-parser-wasm" -version = "1.884.1" +version = "1.894.1" dependencies = [ "getrandom 0.3.4", "wasm-bindgen", @@ -17183,7 +17191,7 @@ dependencies = [ [[package]] name = "windmill-store" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-recursion", @@ -17218,7 +17226,7 @@ dependencies = [ [[package]] name = "windmill-test-utils" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-trait", @@ -17242,7 +17250,7 @@ dependencies = [ [[package]] name = "windmill-trigger" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-trait", @@ -17275,7 +17283,7 @@ dependencies = [ [[package]] name = "windmill-trigger-amqp" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-trait", @@ -17302,7 +17310,7 @@ dependencies = [ [[package]] name = "windmill-trigger-azure" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-trait", @@ -17335,7 +17343,7 @@ dependencies = [ [[package]] name = "windmill-trigger-email" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-trait", @@ -17355,7 +17363,7 @@ dependencies = [ [[package]] name = "windmill-trigger-gcp" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-trait", @@ -17389,7 +17397,7 @@ dependencies = [ [[package]] name = "windmill-trigger-http" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-trait", @@ -17426,7 +17434,7 @@ dependencies = [ [[package]] name = "windmill-trigger-kafka" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-trait", @@ -17449,7 +17457,7 @@ dependencies = [ [[package]] name = "windmill-trigger-mqtt" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-trait", @@ -17473,7 +17481,7 @@ dependencies = [ [[package]] name = "windmill-trigger-nats" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-nats", @@ -17497,7 +17505,7 @@ dependencies = [ [[package]] name = "windmill-trigger-postgres" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-trait", @@ -17532,7 +17540,7 @@ dependencies = [ [[package]] name = "windmill-trigger-sqs" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-trait", @@ -17560,7 +17568,7 @@ dependencies = [ [[package]] name = "windmill-trigger-websocket" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-trait", @@ -17586,7 +17594,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -17606,7 +17614,7 @@ dependencies = [ [[package]] name = "windmill-worker" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-once-cell", @@ -17724,7 +17732,7 @@ dependencies = [ [[package]] name = "windmill-worker-volumes" -version = "1.884.1" +version = "1.894.1" dependencies = [ "bytes", "fs4", @@ -17963,6 +17971,12 @@ version = "0.100.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b39de7c7fe78858b0144c50c3fc000bab3be17d5e9b85b1053871693c7f7415" +[[package]] +name = "windows-link" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4e57b2aae53a240c62b65069a63eaf8d5fa747f5d0d8e670c5210a98847bce4" + [[package]] name = "windows-numerics" version = "0.2.0" @@ -18103,6 +18117,15 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows-sys" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eed2df9f5f458664c87437f6758f0d93085b06433bf66b2b84c23c19f3d2012c" +dependencies = [ + "windows-link 0.101.0", +] + [[package]] name = "windows-targets" version = "0.48.5" @@ -18522,18 +18545,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.65" +version = "0.8.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32bc8a75f879cd6fe53a6bedf3c28f0e1b914c77424fc2be9e2ec85d7d25aff5" +checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.65" +version = "0.8.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8bfd2644ea1681f60cf95029ff18aa8ad1cc3f7b8fe37286f8e473bb29f816b" +checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" dependencies = [ "proc-macro2", "quote", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index a45d448c37..7cc8a60b12 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "windmill" -version = "1.884.1" +version = "1.894.1" authors.workspace = true edition.workspace = true @@ -88,7 +88,7 @@ members = [ exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"] [workspace.package] -version = "1.884.1" +version = "1.894.1" authors = ["Ruben Fiszel "] edition = "2021" @@ -226,12 +226,16 @@ all_sqlx_features = ["all_languages", "enterprise", "enterprise_saml", "embeddin "windmill-git-sync/all_sqlx_features"] [patch.crates-io] -# v0.8.6 plus the fix below and two `#[sqlx::test]`-only changes, both set in .cargo/config.toml: +# v0.8.6 plus the two fixes below and two `#[sqlx::test]`-only changes, both set in .cargo/config.toml: # `SQLX_TEST_TEMPLATE` clones each test database from a template migrated once per migration # set instead of migrating it per test, and `SQLX_TEST_MAX_CONNECTIONS` lifts the cap on the -# connections all test pools share. The rev is tagged `windmill-0.8.6-test-template-c1c5f1f` in -# the fork so it stays fetchable. -# The fix: `Pool::begin` is not cancel-safe on Postgres. sqlx raises the +# connections all test pools share. The rev is tagged `windmill-0.8.6-return-to-pool-timeout-ac66fd0` +# in the fork so it stays fetchable. +# The return-to-pool fix (launchbadge/sqlx#4349): a dropped connection's permit is held while +# sqlx pings it, with no time limit, so a peer that went silent (a Postgres primary after a +# failover) leaks permits until every `acquire()` fails with PoolTimedOut. It bounds that step to +# 5s. Drop it once a release we take carries transact-rs/sqlx#4350. +# The `Pool::begin` fix: `Pool::begin` is not cancel-safe on Postgres. sqlx raises the # transaction depth its rollback-on-drop guard keys on only *after* the BEGIN round trip, so # a cancelled caller (a disconnecting API client, a `timeout`, an aborted task) leaves the # session in a transaction nothing will end, and the pool hands that connection out again — @@ -242,15 +246,17 @@ all_sqlx_features = ["all_languages", "enterprise", "enterprise_saml", "embeddin # inside the sqlx workspace, so patching it alone leaves two incompatible `sqlx-core`s and # `Postgres` stops implementing the `Database` the macros expect. # Changing any of this — a bump, a rebase of the fork, dropping these lines — still compiles -# clean, so run the guard that actually checks the behaviour is still there: +# clean, so run the guards that actually check the behaviour is still there, the first here and +# the second in the fork: # cargo test -p windmill-common --test sqlx_begin_cancel_safe -- --ignored -sqlx = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } -sqlx-core = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } -sqlx-macros = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } -sqlx-macros-core = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } -sqlx-postgres = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } -sqlx-mysql = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } -sqlx-sqlite = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } +# cargo test --test postgres-pool --no-default-features --features postgres,runtime-tokio,macros,migrate +sqlx = { git = "https://github.com/windmill-labs/sqlx", rev = "ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" } +sqlx-core = { git = "https://github.com/windmill-labs/sqlx", rev = "ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" } +sqlx-macros = { git = "https://github.com/windmill-labs/sqlx", rev = "ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" } +sqlx-macros-core = { git = "https://github.com/windmill-labs/sqlx", rev = "ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" } +sqlx-postgres = { git = "https://github.com/windmill-labs/sqlx", rev = "ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" } +sqlx-mysql = { git = "https://github.com/windmill-labs/sqlx", rev = "ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" } +sqlx-sqlite = { git = "https://github.com/windmill-labs/sqlx", rev = "ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" } object_store = { git = "https://github.com/apache/arrow-rs-object-store", rev = "36752c975d4f29e20b57c91f81a10872dcd48ae7" } # Use tiberius main branch for libgssapi 0.8.1 fix (https://github.com/prisma/tiberius/issues/343) tiberius = { git = "https://github.com/prisma/tiberius", rev = "59db57960a14b422fb3a1309aa4aa47880896ff8" } @@ -706,6 +712,7 @@ tracing-opentelemetry = "0.31.0" opentelemetry_sdk = { version = "0.30.0", features = ["rt-tokio", "testing"] } opentelemetry-otlp = { version = "0.30.0", features = ["grpc-tonic", "tls", "http-proto", "gzip-tonic", "zstd-tonic"] } opentelemetry-appender-tracing = "0.30.0" +opentelemetry-http = "0.30.0" opentelemetry-semantic-conventions = { version = "0.30.0", features = ["semconv_experimental"] } opentelemetry-proto = { version = "0.30.0", features = ["with-serde", "gen-tonic"] } prost = "0.13" diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index a1fc20442a..9856fbbc53 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -a403f3ce12fd150dd649098e61562eda1e6a4d81 +b278e6b2bcaa04c27faa7293474d0ac5132dcaf9 diff --git a/backend/migrations/20261124085334_totp_two_factor.down.sql b/backend/migrations/20261124085334_totp_two_factor.down.sql new file mode 100644 index 0000000000..631dced01e --- /dev/null +++ b/backend/migrations/20261124085334_totp_two_factor.down.sql @@ -0,0 +1,7 @@ +ALTER TABLE password + DROP COLUMN IF EXISTS totp_secret, + DROP COLUMN IF EXISTS totp_pending_secret, + DROP COLUMN IF EXISTS totp_last_step, + DROP COLUMN IF EXISTS totp_recovery_codes, + DROP COLUMN IF EXISTS totp_failed_attempts, + DROP COLUMN IF EXISTS totp_failed_since; diff --git a/backend/migrations/20261124085334_totp_two_factor.up.sql b/backend/migrations/20261124085334_totp_two_factor.up.sql new file mode 100644 index 0000000000..0383516d08 --- /dev/null +++ b/backend/migrations/20261124085334_totp_two_factor.up.sql @@ -0,0 +1,7 @@ +ALTER TABLE password + ADD COLUMN IF NOT EXISTS totp_secret TEXT, + ADD COLUMN IF NOT EXISTS totp_pending_secret TEXT, + ADD COLUMN IF NOT EXISTS totp_last_step BIGINT, + ADD COLUMN IF NOT EXISTS totp_recovery_codes TEXT[], + ADD COLUMN IF NOT EXISTS totp_failed_attempts INTEGER NOT NULL DEFAULT 0, + ADD COLUMN IF NOT EXISTS totp_failed_since TIMESTAMPTZ; diff --git a/backend/migrations/20261124161107_concurrency_key_released_at.down.sql b/backend/migrations/20261124161107_concurrency_key_released_at.down.sql new file mode 100644 index 0000000000..fea8b63fd5 --- /dev/null +++ b/backend/migrations/20261124161107_concurrency_key_released_at.down.sql @@ -0,0 +1 @@ +ALTER TABLE concurrency_key DROP COLUMN IF EXISTS released_at; diff --git a/backend/migrations/20261124161107_concurrency_key_released_at.up.sql b/backend/migrations/20261124161107_concurrency_key_released_at.up.sql new file mode 100644 index 0000000000..46eb8a4664 --- /dev/null +++ b/backend/migrations/20261124161107_concurrency_key_released_at.up.sql @@ -0,0 +1,2 @@ +-- When the concurrency limit let in a job it had held back: the time the job was last due. +ALTER TABLE concurrency_key ADD COLUMN IF NOT EXISTS released_at TIMESTAMPTZ; diff --git a/backend/migrations/20261126085023_audit_client_ip_user_agent.down.sql b/backend/migrations/20261126085023_audit_client_ip_user_agent.down.sql new file mode 100644 index 0000000000..5d83f2c95f --- /dev/null +++ b/backend/migrations/20261126085023_audit_client_ip_user_agent.down.sql @@ -0,0 +1,15 @@ +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM pg_class WHERE oid = to_regclass('audit') AND relkind = 'r') THEN + ALTER TABLE audit DROP COLUMN IF EXISTS client_ip, DROP COLUMN IF EXISTS user_agent; + ELSIF EXISTS (SELECT 1 FROM pg_class WHERE oid = to_regclass('audit') AND relkind = 'v') THEN + DROP VIEW audit; + CREATE VIEW audit AS + SELECT workspace_id, id, timestamp, username, operation, action_kind, resource, + parameters, email, span + FROM audit_partitioned WHERE false; + GRANT ALL ON audit TO windmill_user, windmill_admin; + END IF; +END $$; + +ALTER TABLE audit_partitioned DROP COLUMN IF EXISTS client_ip, DROP COLUMN IF EXISTS user_agent; diff --git a/backend/migrations/20261126085023_audit_client_ip_user_agent.up.sql b/backend/migrations/20261126085023_audit_client_ip_user_agent.up.sql new file mode 100644 index 0000000000..dc9115bf23 --- /dev/null +++ b/backend/migrations/20261126085023_audit_client_ip_user_agent.up.sql @@ -0,0 +1,15 @@ +ALTER TABLE audit_partitioned ADD COLUMN IF NOT EXISTS client_ip TEXT, ADD COLUMN IF NOT EXISTS user_agent TEXT; + +-- Older servers read `SELECT * FROM audit_partitioned UNION ALL SELECT * FROM audit`, so the +-- legacy table, or the empty view that replaces it, carries the same columns in the same order. +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM pg_class WHERE oid = to_regclass('audit') AND relkind = 'r') THEN + ALTER TABLE audit ADD COLUMN IF NOT EXISTS client_ip TEXT, ADD COLUMN IF NOT EXISTS user_agent TEXT; + ELSIF EXISTS (SELECT 1 FROM pg_class WHERE oid = to_regclass('audit') AND relkind = 'v') THEN + CREATE OR REPLACE VIEW audit AS + SELECT workspace_id, id, timestamp, username, operation, action_kind, resource, + parameters, email, span, client_ip, user_agent + FROM audit_partitioned WHERE false; + END IF; +END $$; diff --git a/backend/migrations/20261126110005_token_allowed_ips.down.sql b/backend/migrations/20261126110005_token_allowed_ips.down.sql new file mode 100644 index 0000000000..12fba41917 --- /dev/null +++ b/backend/migrations/20261126110005_token_allowed_ips.down.sql @@ -0,0 +1 @@ +ALTER TABLE token DROP COLUMN IF EXISTS allowed_ips; diff --git a/backend/migrations/20261126110005_token_allowed_ips.up.sql b/backend/migrations/20261126110005_token_allowed_ips.up.sql new file mode 100644 index 0000000000..849c3d59ee --- /dev/null +++ b/backend/migrations/20261126110005_token_allowed_ips.up.sql @@ -0,0 +1 @@ +ALTER TABLE token ADD COLUMN IF NOT EXISTS allowed_ips cidr[]; diff --git a/backend/migrations/20261127074016_token_superadmin_follows_owner.down.sql b/backend/migrations/20261127074016_token_superadmin_follows_owner.down.sql new file mode 100644 index 0000000000..8f9ea78eb7 --- /dev/null +++ b/backend/migrations/20261127074016_token_superadmin_follows_owner.down.sql @@ -0,0 +1,2 @@ +DROP TRIGGER IF EXISTS password_superadmin_demote_tokens ON password; +DROP FUNCTION IF EXISTS demote_tokens_of_demoted_owner(); diff --git a/backend/migrations/20261127074016_token_superadmin_follows_owner.up.sql b/backend/migrations/20261127074016_token_superadmin_follows_owner.up.sql new file mode 100644 index 0000000000..b0bf79fcae --- /dev/null +++ b/backend/migrations/20261127074016_token_superadmin_follows_owner.up.sql @@ -0,0 +1,50 @@ +-- A token's `super_admin` column is what grants it superadmin power at auth time, so it must not +-- outlive the owner's: whatever path demotes or deletes a superadmin `password` row, that +-- address's tokens lose the flag. Deferred to commit and judged on the committed state, so a path +-- that deletes and re-inserts the rows (the global user import) demotes only the addresses that +-- come back without superadmin. An email change is not a demotion and does not fire: SCIM's +-- rename moves the account but leaves its tokens under the old address. +-- Promotion is left to the application, which deliberately does not elevate MCP tokens. +CREATE OR REPLACE FUNCTION demote_tokens_of_demoted_owner() +RETURNS TRIGGER AS $$ +BEGIN + WITH demoted AS ( + UPDATE token SET super_admin = false + WHERE email = OLD.email + AND super_admin + AND NOT EXISTS (SELECT 1 FROM password WHERE email = OLD.email AND super_admin) + RETURNING token_prefix + ) + INSERT INTO notify_event (channel, payload) + SELECT 'notify_token_invalidation', token_prefix FROM demoted; + RETURN NULL; +END; +$$ LANGUAGE plpgsql SECURITY DEFINER; + +DO +$do$ +BEGIN + EXECUTE format( + 'ALTER FUNCTION demote_tokens_of_demoted_owner() SET search_path = %I, pg_temp', + current_schema() + ); +END +$do$; +REVOKE EXECUTE ON FUNCTION demote_tokens_of_demoted_owner() FROM PUBLIC; + +DROP TRIGGER IF EXISTS password_superadmin_demote_tokens ON password; +CREATE CONSTRAINT TRIGGER password_superadmin_demote_tokens +AFTER UPDATE OF super_admin OR DELETE ON password +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW +WHEN (OLD.super_admin) +EXECUTE FUNCTION demote_tokens_of_demoted_owner(); + +-- Tokens already left with the flag by an owner who lost it. A token whose address has no +-- `password` row is left alone: a SCIM rename and the subprocesses of dedicated workers and +-- runner groups both produce one, and cannot be told apart from a deleted account's. +UPDATE token t SET super_admin = false + FROM password p + WHERE p.email = t.email + AND t.super_admin + AND NOT p.super_admin; diff --git a/backend/migrations/20261127075314_token_admin_rights.down.sql b/backend/migrations/20261127075314_token_admin_rights.down.sql new file mode 100644 index 0000000000..30968704d9 --- /dev/null +++ b/backend/migrations/20261127075314_token_admin_rights.down.sql @@ -0,0 +1 @@ +ALTER TABLE token DROP COLUMN IF EXISTS admin; diff --git a/backend/migrations/20261127075314_token_admin_rights.up.sql b/backend/migrations/20261127075314_token_admin_rights.up.sql new file mode 100644 index 0000000000..ed38ac11e7 --- /dev/null +++ b/backend/migrations/20261127075314_token_admin_rights.up.sql @@ -0,0 +1,4 @@ +-- Whether a token carries its owner's workspace admin rights. Every insert names it; the default +-- covers only rows written before it existed and servers that predate it during an upgrade, which +-- must keep minting admin-capable sessions. Flip it to false once no such server can be running. +ALTER TABLE token ADD COLUMN IF NOT EXISTS admin BOOLEAN NOT NULL DEFAULT true; diff --git a/backend/migrations/20261127105444_token_email_index.down.sql b/backend/migrations/20261127105444_token_email_index.down.sql new file mode 100644 index 0000000000..899c5e0252 --- /dev/null +++ b/backend/migrations/20261127105444_token_email_index.down.sql @@ -0,0 +1 @@ +DROP INDEX IF EXISTS token_email_idx; diff --git a/backend/migrations/20261127105444_token_email_index.up.sql b/backend/migrations/20261127105444_token_email_index.up.sql new file mode 100644 index 0000000000..45c51e2d85 --- /dev/null +++ b/backend/migrations/20261127105444_token_email_index.up.sql @@ -0,0 +1,8 @@ +-- Serves every per-user token listing (`list_tokens`, the token risk counts), which otherwise +-- scans the whole table, sessions and job tokens included. +-- Dropped before it is built because the OVERRIDDEN_MIGRATIONS rewrite in +-- windmill-api/src/db.rs runs both CONCURRENTLY: an interrupted concurrent build leaves an +-- invalid index that IF NOT EXISTS would skip rebuilding. +DROP INDEX IF EXISTS token_email_idx; + +CREATE INDEX IF NOT EXISTS token_email_idx ON token (email); diff --git a/backend/migrations/20261127105445_token_risk_view.down.sql b/backend/migrations/20261127105445_token_risk_view.down.sql new file mode 100644 index 0000000000..8de051cb6f --- /dev/null +++ b/backend/migrations/20261127105445_token_risk_view.down.sql @@ -0,0 +1 @@ +DROP VIEW IF EXISTS token_risk; diff --git a/backend/migrations/20261127105445_token_risk_view.up.sql b/backend/migrations/20261127105445_token_risk_view.up.sql new file mode 100644 index 0000000000..903796f220 --- /dev/null +++ b/backend/migrations/20261127105445_token_risk_view.up.sql @@ -0,0 +1,65 @@ +-- The risks a token review flags, computed once for the user's token list and the superadmin +-- review (windmill-api-users/src/users.rs). `self_managed` marks a token the server mints and +-- expires or renews on its own, which nobody manages by hand; its `risks` are empty. The 90 days +-- are mirrored by STALE_TOKEN_DAYS in frontend/src/lib/components/settings/tokenRisks.ts, +-- which only words them. `admin` and `super_admin` are the rights the token carries, as +-- `tokens/list` reports them: minted with them (a session always is) and still held by the owner. +CREATE OR REPLACE VIEW token_risk AS +SELECT + t.email, + t.label, + t.token_prefix, + t.expiration, + t.created_at, + t.last_used_at, + t.scopes, + t.workspace_id, + t.read_only, + t.allowed_ips, + r.admin, + r.super_admin, + m.self_managed, + CASE WHEN m.self_managed THEN ARRAY[]::text[] ELSE array_remove(ARRAY[ + -- Scopes or read-only mode narrow a token's rights; a job tag filter alone does not + -- (windmill-api-auth/src/scopes.rs). + CASE WHEN m.unrestricted AND r.super_admin THEN 'superadmin' END, + CASE WHEN m.unrestricted AND NOT r.super_admin AND r.admin THEN 'admin' END, + CASE WHEN t.workspace_id IS NULL THEN 'all_workspaces' END, + CASE WHEN t.expiration IS NULL THEN 'never_expires' END, + CASE WHEN t.last_used_at < now() - interval '90 days' THEN 'unused' END + ], NULL) END AS risks +FROM token t +LEFT JOIN ( + SELECT email, array_agg(workspace_id) AS admin_of + FROM usr WHERE is_admin AND NOT disabled GROUP BY email +) a ON a.email = t.email +LEFT JOIN password p ON p.email = t.email +CROSS JOIN LATERAL ( + SELECT + t.admin AND a.admin_of IS NOT NULL + AND (t.workspace_id IS NULL OR t.workspace_id = ANY(a.admin_of)) AS admin, + (t.super_admin OR t.label = 'session') IS TRUE AND COALESCE(p.super_admin, false) + AS super_admin +) r +CROSS JOIN LATERAL ( + SELECT + -- A job token, or a label only the server can mint (`is_server_minted_label`). + (t.job IS NOT NULL + OR t.label IN ('session', 'guest_session', 'ephemeral-script') + OR starts_with(t.label, 'ephemeral-webhook-') + OR starts_with(t.label, 'ephemeral-script-end-user-') + OR starts_with(t.label, 'mcp-oauth-') + -- `tokens/create` accepts these labels too, so only a lifetime as short as the + -- system's own (72h for the editor's language server at most, plus a day for the + -- browser's clock, which sets it) proves the token is one of those rather than a + -- long-lived token borrowing the label. + OR ((t.label = 'debugger-token' + OR lower(t.label) LIKE 'ephemeral%' + OR starts_with(t.label, 'embed_app:') + OR starts_with(t.label, 'sdk_app:') + OR starts_with(t.label, 'impersonation:')) + AND t.expiration <= t.created_at + interval '4 days')) IS TRUE AS self_managed, + NOT t.read_only + AND NOT EXISTS (SELECT 1 FROM unnest(t.scopes) s WHERE NOT starts_with(s, 'if_jobs:filter_tags:')) + AS unrestricted +) m; diff --git a/backend/migrations/20261127105446_audit_peer_ip_forwarded_for.down.sql b/backend/migrations/20261127105446_audit_peer_ip_forwarded_for.down.sql new file mode 100644 index 0000000000..747d674957 --- /dev/null +++ b/backend/migrations/20261127105446_audit_peer_ip_forwarded_for.down.sql @@ -0,0 +1,15 @@ +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM pg_class WHERE oid = to_regclass('audit') AND relkind = 'r') THEN + ALTER TABLE audit DROP COLUMN IF EXISTS peer_ip, DROP COLUMN IF EXISTS forwarded_for; + ELSIF EXISTS (SELECT 1 FROM pg_class WHERE oid = to_regclass('audit') AND relkind = 'v') THEN + DROP VIEW audit; + CREATE VIEW audit AS + SELECT workspace_id, id, timestamp, username, operation, action_kind, resource, + parameters, email, span, client_ip, user_agent + FROM audit_partitioned WHERE false; + GRANT ALL ON audit TO windmill_user, windmill_admin; + END IF; +END $$; + +ALTER TABLE audit_partitioned DROP COLUMN IF EXISTS peer_ip, DROP COLUMN IF EXISTS forwarded_for; diff --git a/backend/migrations/20261127105446_audit_peer_ip_forwarded_for.up.sql b/backend/migrations/20261127105446_audit_peer_ip_forwarded_for.up.sql new file mode 100644 index 0000000000..b348032f6d --- /dev/null +++ b/backend/migrations/20261127105446_audit_peer_ip_forwarded_for.up.sql @@ -0,0 +1,15 @@ +ALTER TABLE audit_partitioned ADD COLUMN IF NOT EXISTS peer_ip TEXT, ADD COLUMN IF NOT EXISTS forwarded_for TEXT; + +-- Older servers read `SELECT * FROM audit_partitioned UNION ALL SELECT * FROM audit`, so the +-- legacy table, or the empty view that replaces it, carries the same columns in the same order. +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM pg_class WHERE oid = to_regclass('audit') AND relkind = 'r') THEN + ALTER TABLE audit ADD COLUMN IF NOT EXISTS peer_ip TEXT, ADD COLUMN IF NOT EXISTS forwarded_for TEXT; + ELSIF EXISTS (SELECT 1 FROM pg_class WHERE oid = to_regclass('audit') AND relkind = 'v') THEN + CREATE OR REPLACE VIEW audit AS + SELECT workspace_id, id, timestamp, username, operation, action_kind, resource, + parameters, email, span, client_ip, user_agent, peer_ip, forwarded_for + FROM audit_partitioned WHERE false; + END IF; +END $$; diff --git a/backend/oauth_connect.json b/backend/oauth_connect.json index 48957fee2f..f89f992c10 100644 --- a/backend/oauth_connect.json +++ b/backend/oauth_connect.json @@ -302,7 +302,10 @@ { "value": "https://www.googleapis.com/auth/admin.directory.orgunit", "label": "Read and manage organizational units" }, { "value": "https://www.googleapis.com/auth/admin.directory.orgunit.readonly", "label": "Read organizational units" }, { "value": "https://www.googleapis.com/auth/admin.directory.user.security", "label": "Manage user security settings" }, - { "value": "https://www.googleapis.com/auth/admin.reports.audit.readonly", "label": "Read audit logs (login, admin, Drive, token activity)" } + { "value": "https://www.googleapis.com/auth/admin.reports.audit.readonly", "label": "Read audit logs (login, admin, Drive, token activity)" }, + { "value": "https://www.googleapis.com/auth/drive.readonly", "label": "Read Drive files" }, + { "value": "https://www.googleapis.com/auth/calendar.readonly", "label": "Read calendars" }, + { "value": "https://www.googleapis.com/auth/calendar.events", "label": "Read and manage calendar events" } ], "extra_params": { "access_type": "offline", diff --git a/backend/parsers/windmill-parser-py-imports/src/lib.rs b/backend/parsers/windmill-parser-py-imports/src/lib.rs index f1718c6d94..59dd565f2c 100644 --- a/backend/parsers/windmill-parser-py-imports/src/lib.rs +++ b/backend/parsers/windmill-parser-py-imports/src/lib.rs @@ -749,11 +749,17 @@ fn extract_nimports_from_content( locked_version } -const STDIMPORTS: [&str; 303] = [ +// Union of `sys.stdlib_module_names` over every `PyVAlias` version (3.10 to 3.15), `_` +// written as `-` like the inferred package names. Regenerate when a version is added; +// modules a later version removed stay, since older workers still ship them. +const STDIMPORTS: [&str; 332] = [ "--future--", "-abc", "-aix-support", + "-android-support", + "-apple-support", "-ast", + "-ast-unparse", "-asyncio", "-bisect", "-blake2", @@ -768,6 +774,7 @@ const STDIMPORTS: [&str; 303] = [ "-codecs-tw", "-collections", "-collections-abc", + "-colorize", "-compat-pickle", "-compression", "-contextvars", @@ -786,18 +793,25 @@ const STDIMPORTS: [&str; 303] = [ "-gdbm", "-hashlib", "-heapq", + "-hmac", "-imp", + "-interpchannels", + "-interpqueues", + "-interpreters", "-io", + "-ios-support", "-json", "-locale", "-lsprof", "-lzma", "-markupbase", + "-math-integer", "-md5", "-msi", "-multibytecodec", "-multiprocessing", "-opcode", + "-opcode-metadata", "-operator", "-osx-support", "-overlapped", @@ -805,11 +819,18 @@ const STDIMPORTS: [&str; 303] = [ "-posixshmem", "-posixsubprocess", "-py-abc", + "-py-warnings", + "-pydatetime", "-pydecimal", "-pyio", + "-pylong", + "-pyrepl", "-queue", "-random", + "-remote-debugging", + "-scproxy", "-sha1", + "-sha2", "-sha256", "-sha3", "-sha512", @@ -824,20 +845,27 @@ const STDIMPORTS: [&str; 303] = [ "-string", "-strptime", "-struct", + "-suggestions", "-symtable", + "-sysconfig", "-thread", "-threading-local", "-tkinter", + "-tokenize", "-tracemalloc", + "-types", + "-typing", "-uuid", "-warnings", "-weakref", "-weakrefset", "-winapi", + "-wmi", "-zoneinfo", - "zoneinfo", + "-zstd", "abc", "aifc", + "annotationlib", "antigravity", "argparse", "array", @@ -867,6 +895,7 @@ const STDIMPORTS: [&str; 303] = [ "collections", "colorsys", "compileall", + "compression", "concurrent", "configparser", "contextlib", @@ -963,6 +992,7 @@ const STDIMPORTS: [&str; 303] = [ "posixpath", "pprint", "profile", + "profiling", "pstats", "pty", "pwd", @@ -1024,6 +1054,7 @@ const STDIMPORTS: [&str; 303] = [ "tkinter", "token", "tokenize", + "tomllib", "trace", "traceback", "tracemalloc", @@ -1052,5 +1083,6 @@ const STDIMPORTS: [&str; 303] = [ "zipfile", "zipimport", "zlib", + "zoneinfo", "", ]; diff --git a/backend/parsers/windmill-parser-py-imports/tests/tests.rs b/backend/parsers/windmill-parser-py-imports/tests/tests.rs index 6d3d75a239..c1214c4140 100644 --- a/backend/parsers/windmill-parser-py-imports/tests/tests.rs +++ b/backend/parsers/windmill-parser-py-imports/tests/tests.rs @@ -157,6 +157,24 @@ def main(): Ok(()) } + #[test] + fn test_recent_stdlib_modules_not_inferred() -> anyhow::Result<()> { + let code = " +import tomllib +import annotationlib +from compression import zstd +import requests + +def main(): + return tomllib.loads(\"a = 1\") +"; + assert_eq!( + parse_code_for_imports(code, "f/foo/bar")?, + vec![auto("requests")] + ); + Ok(()) + } + #[test] fn test_parse_imports_recent_syntax_before_main() -> anyhow::Result<()> { let code = r#" diff --git a/backend/parsers/windmill-parser-wasm/Cargo.lock b/backend/parsers/windmill-parser-wasm/Cargo.lock index e7f42d20de..f792a4eca6 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.lock +++ b/backend/parsers/windmill-parser-wasm/Cargo.lock @@ -6340,7 +6340,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windmill-common" -version = "1.884.1" +version = "1.894.1" dependencies = [ "aes-gcm", "aho-corasick", @@ -6430,7 +6430,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.884.1" +version = "1.894.1" dependencies = [ "proc-macro2", "quote", @@ -6442,7 +6442,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.884.1" +version = "1.894.1" dependencies = [ "convert_case", "serde", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "lazy_static", @@ -6463,7 +6463,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "serde_json", @@ -6475,7 +6475,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "gosyn", @@ -6487,7 +6487,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "lazy_static", @@ -6499,7 +6499,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "serde_json", @@ -6511,7 +6511,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "nu-parser", @@ -6522,7 +6522,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6533,7 +6533,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6545,7 +6545,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "ruff_python_ast", @@ -6556,7 +6556,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "async-recursion", @@ -6579,7 +6579,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "serde_json", @@ -6591,7 +6591,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "lazy_static", @@ -6605,7 +6605,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "convert_case", @@ -6622,7 +6622,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "lazy_static", @@ -6635,7 +6635,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "serde", @@ -6647,7 +6647,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "lazy_static", @@ -6665,7 +6665,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -6681,7 +6681,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "ruff_python_ast", @@ -6698,7 +6698,7 @@ dependencies = [ [[package]] name = "windmill-parser-wasm" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -6730,7 +6730,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "lazy_static", @@ -6744,7 +6744,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.884.1" +version = "1.894.1" dependencies = [ "anyhow", "bitflags", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index d06a874c26..bdd04317ef 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.toml +++ b/backend/parsers/windmill-parser-wasm/Cargo.toml @@ -12,7 +12,7 @@ resolver = "2" members = ["."] [workspace.package] -version = "1.884.1" +version = "1.894.1" edition = "2021" authors = ["Ruben Fiszel "] diff --git a/backend/src/main.rs b/backend/src/main.rs index db5abf21d2..f86543261c 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -8,8 +8,9 @@ use anyhow::Context; use monitor::{ flush_pending_log_files_to_object_store, load_base_url, load_otel, - reload_critical_alerts_on_db_oversize, reload_delete_logs_periodically_setting, - reload_indexer_config, reload_instance_python_version_setting, reload_maven_repos_setting, + reload_cran_repo_url_setting, reload_critical_alerts_on_db_oversize, + reload_delete_logs_periodically_setting, reload_indexer_config, + reload_instance_python_version_setting, reload_maven_repos_setting, reload_maven_settings_xml_setting, reload_no_default_maven_setting, reload_nuget_config_setting, reload_powershell_repo_pat_setting, reload_powershell_repo_url_setting, reload_ruby_repos_setting, @@ -61,14 +62,15 @@ use windmill_common::{ OAUTH_SETTING, OTEL_SETTING, OTEL_TRACES_RETENTION_SECS_SETTING, OTEL_TRACING_PROXY_SETTING, PIP_INDEX_URL_SETTING, POWERSHELL_REPO_PAT_SETTING, POWERSHELL_REPO_URL_SETTING, PREVIEW_TAGS_OVERRIDE_SETTING, REQUEST_SIZE_LIMIT_SETTING, - REQUIRE_PREEXISTING_USER_FOR_OAUTH_SETTING, RESTART_COORDINATION_SETTING, - RETENTION_PERIOD_SECS_OVERRIDES_SETTING, RETENTION_PERIOD_SECS_SETTING, RUBY_REPOS_SETTING, - SAML_METADATA_SETTING, SANDBOX_IMAGE_CACHE_MAX_MB_SETTING, - SANDBOX_IMAGE_DEFAULT_REGISTRY_SETTING, SANDBOX_IMAGE_MAX_SIZE_MB_SETTING, - SANDBOX_IMAGE_PULL_POLICY_SETTING, SANDBOX_REGISTRY_AUTH_SETTING, SCIM_TOKEN_SETTING, - SERVICE_LOG_RETENTION_SECS_SETTING, SMTP_SETTING, STORE_AUDIT_LOGS_S3_SETTING, - SYNC_HUB_RESOURCE_TYPES_DAILY_SETTING, TEAMS_SETTING, TIMEOUT_WAIT_RESULT_SETTING, - UV_EXCLUDE_NEWER_SETTING, UV_INDEX_STRATEGY_SETTING, UV_PYTHON_INSTALL_MIRROR_SETTING, + REQUIRE_PREEXISTING_USER_FOR_OAUTH_SETTING, REQUIRE_TOTP_SETTING, + RESTART_COORDINATION_SETTING, RETENTION_PERIOD_SECS_OVERRIDES_SETTING, + RETENTION_PERIOD_SECS_SETTING, RUBY_REPOS_SETTING, SAML_METADATA_SETTING, + SANDBOX_IMAGE_CACHE_MAX_MB_SETTING, SANDBOX_IMAGE_DEFAULT_REGISTRY_SETTING, + SANDBOX_IMAGE_MAX_SIZE_MB_SETTING, SANDBOX_IMAGE_PULL_POLICY_SETTING, + SANDBOX_REGISTRY_AUTH_SETTING, SCIM_TOKEN_SETTING, SERVICE_LOG_RETENTION_SECS_SETTING, + SMTP_SETTING, STORE_AUDIT_LOGS_S3_SETTING, SYNC_HUB_RESOURCE_TYPES_DAILY_SETTING, + TEAMS_SETTING, TIMEOUT_WAIT_RESULT_SETTING, UV_EXCLUDE_NEWER_SETTING, + UV_INDEX_STRATEGY_SETTING, UV_PYTHON_INSTALL_MIRROR_SETTING, WORKSPACE_FAIRNESS_DURATION_SECS_SETTING, WORKSPACE_FAIRNESS_ENABLED_SETTING, WORKSPACE_FAIRNESS_MAX_PERCENT_SETTING, WORKSPACE_FAIRNESS_MIN_TOTAL_SETTING, WORKSPACE_MAX_QUEUED_JOBS_SETTING, WORKSPACE_REGISTRIES_SETTING, @@ -136,14 +138,15 @@ use crate::monitor::{ load_dev_workspace_isolation_skip_non_dev_forks, load_dev_workspace_tag_suffix, load_disable_password_login, load_fork_workspace_tag_append_fork_suffix, load_keep_job_dir, load_mcp_disable_token_query_param, load_metrics_debug_enabled, load_preview_tags_override, - load_require_preexisting_user, load_retention_period_overrides, load_tag_per_workspace_enabled, - load_tag_per_workspace_workspaces, load_workspace_fairness_duration_secs, - load_workspace_fairness_enabled, load_workspace_fairness_max_percent, - load_workspace_fairness_min_total, load_workspace_max_queued_jobs, monitor_db, - reload_app_workspaced_route_setting, reload_audit_log_retention_days_setting, - reload_base_url_setting, reload_bun_install_min_release_age_setting, - reload_bunfig_install_scopes_setting, reload_cargo_registries_setting, - reload_critical_alert_mute_ui_setting, reload_critical_alert_mute_zombie_job_restart_setting, + load_require_preexisting_user, load_require_totp, load_retention_period_overrides, + load_tag_per_workspace_enabled, load_tag_per_workspace_workspaces, + load_workspace_fairness_duration_secs, load_workspace_fairness_enabled, + load_workspace_fairness_max_percent, load_workspace_fairness_min_total, + load_workspace_max_queued_jobs, monitor_db, reload_app_workspaced_route_setting, + reload_audit_log_retention_days_setting, reload_base_url_setting, + reload_bun_install_min_release_age_setting, reload_bunfig_install_scopes_setting, + reload_cargo_registries_setting, reload_critical_alert_mute_ui_setting, + reload_critical_alert_mute_zombie_job_restart_setting, reload_critical_alerts_on_token_expiry_setting, reload_critical_error_channels_setting, reload_extra_pip_index_url_setting, reload_http_route_default_allowed_origins_setting, reload_http_route_workspaced_route_setting, reload_hub_api_secret_setting, @@ -1260,6 +1263,9 @@ Windmill Community Edition {GIT_VERSION} #[cfg(all(feature = "private", feature = "enterprise"))] let otel_killpill_rx = killpill_rx.resubscribe(); + if !(server_mode || mcp_mode || indexer_mode) { + windmill_common::client_ip::serve_local_jobs_only(); + } let server_f = async { if !is_agent { if let Some(db) = conn.as_sql() { @@ -1614,6 +1620,23 @@ Windmill Community Edition {GIT_VERSION} // internal url so the workers get past that oneshot before it builds its router. // Ordering `server_f` first makes them wait out the whole build instead. if mcp_mode { + // No monitor loop delivers setting changes here, and the MCP server enforces token IP + // allowlists too: a proxy the main API stopped trusting must not stay trusted here. + if let Some(db) = conn.as_sql() { + let db = db.clone(); + let mut killpill_rx = killpill_tx.subscribe(); + tokio::spawn(async move { + loop { + tokio::select! { + _ = killpill_rx.recv() => return, + _ = tokio::time::sleep(Duration::from_secs(*LISTEN_NEW_EVENTS_INTERVAL_SEC)) => { + windmill_common::client_ip::reload(&db).await; + windmill_common::instance_ip_allowlist::reload(&db).await; + } + } + } + }); + } futures::try_join!(workers_f, server_f)?; } else { futures::try_join!( @@ -2044,6 +2067,9 @@ async fn process_notify_event( MAVEN_SETTINGS_XML_SETTING => reload_maven_settings_xml_setting(conn).await, NO_DEFAULT_MAVEN_SETTING => reload_no_default_maven_setting(conn).await, RUBY_REPOS_SETTING => reload_ruby_repos_setting(conn).await, + windmill_common::global_settings::CRAN_REPO_URL_SETTING => { + reload_cran_repo_url_setting(conn).await + } CARGO_REGISTRIES_SETTING => reload_cargo_registries_setting(conn).await, WORKSPACE_REGISTRIES_SETTING => reload_workspace_registries_setting(conn).await, HUB_API_SECRET_SETTING => reload_hub_api_secret_setting(conn).await, @@ -2070,6 +2096,12 @@ async fn process_notify_event( DISABLE_PASSWORD_LOGIN_SETTING => { load_disable_password_login(db).await; } + REQUIRE_TOTP_SETTING => { + load_require_totp(db).await; + } + k if windmill_common::client_ip::SETTING_KEYS.contains(&k) => { + windmill_common::client_ip::reload(db).await; + } windmill_common::global_settings::WORKSPACE_ROLES_SETTING => { windmill_common::roles::invalidate_all_roles_cache(); } @@ -2079,6 +2111,9 @@ async fn process_notify_event( windmill_common::global_settings::MCP_EXTERNAL_IDP_SETTING => { crate::monitor::load_mcp_external_idp(db).await; } + windmill_common::global_settings::INSTANCE_IP_ALLOWLIST_SETTING => { + windmill_common::instance_ip_allowlist::reload(db).await; + } API_BASE_URL_SETTING => { load_api_base_url(db).await; } diff --git a/backend/src/monitor.rs b/backend/src/monitor.rs index 6c70e666a8..49a4a590e6 100644 --- a/backend/src/monitor.rs +++ b/backend/src/monitor.rs @@ -75,8 +75,8 @@ use windmill_common::{ OTEL_SETTING, OTEL_TRACES_RETENTION_SECS_SETTING, OTEL_TRACING_PROXY_SETTING, PIP_INDEX_URL_SETTING, POWERSHELL_REPO_PAT_SETTING, POWERSHELL_REPO_URL_SETTING, PREVIEW_TAGS_OVERRIDE_SETTING, REQUEST_SIZE_LIMIT_SETTING, - REQUIRE_PREEXISTING_USER_FOR_OAUTH_SETTING, RETENTION_PERIOD_SECS_SETTING, - SAML_METADATA_SETTING, SANDBOX_IMAGE_CACHE_MAX_MB_SETTING, + REQUIRE_PREEXISTING_USER_FOR_OAUTH_SETTING, REQUIRE_TOTP, REQUIRE_TOTP_SETTING, + RETENTION_PERIOD_SECS_SETTING, SAML_METADATA_SETTING, SANDBOX_IMAGE_CACHE_MAX_MB_SETTING, SANDBOX_IMAGE_DEFAULT_REGISTRY_SETTING, SANDBOX_IMAGE_MAX_SIZE_MB_SETTING, SANDBOX_IMAGE_PULL_POLICY_SETTING, SANDBOX_REGISTRY_AUTH_SETTING, SCIM_TOKEN_SETTING, SERVICE_LOG_RETENTION_SECS_SETTING, SMTP_SETTING, STORE_AUDIT_LOGS_S3_SETTING, @@ -111,7 +111,7 @@ use windmill_common::{ CRITICAL_ALERT_MUTE_ZOMBIE_JOB_RESTART, CRITICAL_ERROR_CHANNELS, DB, DEFAULT_HUB_BASE_URL, DEFAULT_OTEL_TRACES_RETENTION_SECS, DEFAULT_SERVICE_LOG_RETENTION_SECS, HUB_BASE_URL, JOB_RETENTION_SECS, JOB_RETENTION_SECS_OVERRIDES, JOB_RETENTION_SECS_OVERRIDES_LOADED, - METRICS_DEBUG_ENABLED, METRICS_ENABLED, MONITOR_LOGS_ON_OBJECT_STORE, OTEL_LOGS_ENABLED, + METRICS_DEBUG_ENABLED, METRICS_ENABLED, MONITOR_LOGS_ON_OBJECT_STORE, OtelAuditLogsExport, OTEL_AUDIT_LOGS_EXPORT, OTEL_LOGS_ENABLED, OTEL_LOGS_EXCLUDE_AUDIT, OTEL_METRICS_ENABLED, OTEL_TRACING_ENABLED, STORE_AUDIT_LOGS_S3, }; use windmill_common::{ @@ -317,6 +317,14 @@ pub async fn initial_load( false, |v| async move { apply_mcp_external_idp(v) }, ); + // Every mode: a worker's API is served too, and the trust must be in place before the + // server accepts requests. + pass.action(windmill_common::client_ip::reload(db)); + pass.setting( + windmill_common::global_settings::INSTANCE_IP_ALLOWLIST_SETTING, + false, + |v| async move { windmill_common::instance_ip_allowlist::apply_setting(v.as_ref()) }, + ); pass.setting(API_BASE_URL_SETTING, false, |v| async move { apply_api_base_url(v) }); @@ -408,6 +416,9 @@ pub async fn initial_load( pass.setting(DISABLE_PASSWORD_LOGIN_SETTING, false, |v| async move { apply_disable_password_login(v) }); + pass.setting(REQUIRE_TOTP_SETTING, false, |v| async move { + apply_require_totp(v) + }); pass.action(async move { if let Err(e) = reload_critical_alerts_on_db_oversize(db).await { tracing::error!( @@ -777,6 +788,11 @@ pub async fn initial_load( "RUBY_REPOS", windmill_worker::RUBY_REPOS.clone(), ); + pass.option_setting( + gs::CRAN_REPO_URL_SETTING, + "CRAN_REPO_URL", + windmill_worker::CRAN_REPO_URL.clone(), + ); pass.option_setting( gs::CARGO_REGISTRIES_SETTING, "CARGO_REGISTRIES", @@ -802,6 +818,15 @@ pub fn apply_metrics_enabled(value: Option) { struct OtelSetting { metrics_enabled: Option, logs_enabled: Option, + logs_exclude_audit: Option, + audit_logs_enabled: Option, + #[serde(default, deserialize_with = "empty_as_none")] + audit_logs_endpoint: Option, + #[serde(default, deserialize_with = "empty_as_none")] + audit_logs_headers: Option, + #[serde(default, deserialize_with = "empty_as_none")] + audit_logs_protocol: Option, + audit_logs_workspaces: Option>, tracing_enabled: Option, #[serde(default, deserialize_with = "empty_as_none")] otel_exporter_otlp_endpoint: Option, @@ -837,6 +862,37 @@ pub async fn load_otel(db: &DB) { OTEL_METRICS_ENABLED.store(metrics_enabled, Ordering::Relaxed); OTEL_LOGS_ENABLED.store(logs_enabled, Ordering::Relaxed); + + let env_bool = |var: &str| { + std::env::var(var) + .map(|x| x.parse::().unwrap_or(false)) + .unwrap_or(false) + }; + let logs_exclude_audit = o + .logs_exclude_audit + .unwrap_or_else(|| env_bool("OTEL_LOGS_EXCLUDE_AUDIT")); + OTEL_LOGS_EXCLUDE_AUDIT.store(logs_exclude_audit, Ordering::Relaxed); + let audit_logs = OtelAuditLogsExport::new( + o.audit_logs_enabled + .unwrap_or_else(|| env_bool("OTEL_AUDIT_LOGS_ENABLED")), + o.audit_logs_endpoint + .or_else(|| std::env::var("OTEL_AUDIT_LOGS_ENDPOINT").ok()), + o.audit_logs_headers + .or_else(|| std::env::var("OTEL_AUDIT_LOGS_HEADERS").ok()), + o.audit_logs_protocol + .or_else(|| std::env::var("OTEL_AUDIT_LOGS_PROTOCOL").ok()), + // A saved empty list means every workspace and does not fall back to the + // environment, so clearing the list in the UI cannot bring an env list back. + o.audit_logs_workspaces.or_else(|| { + std::env::var("OTEL_AUDIT_LOGS_WORKSPACES") + .ok() + .map(|v| v.split(',').map(str::to_string).collect()) + }), + ); + let audit_logs_endpoint = audit_logs.as_ref().map(|a| a.endpoint.clone()); + if let Ok(mut export) = OTEL_AUDIT_LOGS_EXPORT.write() { + *export = audit_logs; + } OTEL_TRACING_ENABLED.store(tracing_enabled, Ordering::Relaxed); let endpoint = if let Some(endpoint) = o.otel_exporter_otlp_endpoint { @@ -867,7 +923,7 @@ pub async fn load_otel(db: &DB) { std::env::set_var("OTEL_EXPORTER_OTLP_COMPRESSION", compression); } } - println!("OTEL settings loaded: tracing ({tracing_enabled}), logs ({logs_enabled}), metrics ({metrics_enabled}), endpoint ({:?}), headers defined: ({})", + println!("OTEL settings loaded: tracing ({tracing_enabled}), logs ({logs_enabled}, without audit: {logs_exclude_audit}), audit logs endpoint ({audit_logs_endpoint:?}), metrics ({metrics_enabled}), endpoint ({:?}), headers defined: ({})", endpoint, headers.is_some()); } else { tracing::error!("Error deserializing otel settings"); @@ -1750,6 +1806,21 @@ pub async fn load_disable_password_login(db: &DB) { }; } +pub async fn load_require_totp(db: &DB) { + match load_value_from_global_settings(db, REQUIRE_TOTP_SETTING).await { + Ok(v) => apply_require_totp(v), + Err(e) => tracing::error!("Error loading require_totp setting: {e:#}"), + }; +} + +pub fn apply_require_totp(value: Option) { + match value { + Some(serde_json::Value::Bool(t)) => REQUIRE_TOTP.store(t, Ordering::Relaxed), + None => REQUIRE_TOTP.store(false, Ordering::Relaxed), + _ => (), + }; +} + pub fn apply_disable_password_login(value: Option) { match value { Some(serde_json::Value::Bool(t)) => DISABLE_PASSWORD_LOGIN.store(t, Ordering::Relaxed), @@ -3210,6 +3281,16 @@ pub async fn reload_ruby_repos_setting(conn: &Connection) { .await; } +pub async fn reload_cran_repo_url_setting(conn: &Connection) { + reload_option_setting_with_tracing( + conn, + windmill_common::global_settings::CRAN_REPO_URL_SETTING, + "CRAN_REPO_URL", + windmill_worker::CRAN_REPO_URL.clone(), + ) + .await; +} + pub async fn reload_workspace_registries_setting(conn: &Connection) { match load_value_from_global_settings_with_conn( conn, diff --git a/backend/tests/app_preview_auth.rs b/backend/tests/app_preview_auth.rs index 9f6e77f61c..30e5bc189a 100644 --- a/backend/tests/app_preview_auth.rs +++ b/backend/tests/app_preview_auth.rs @@ -315,8 +315,8 @@ async fn test_app_preview_authorization(db: Pool) -> anyhow::Result<() // 11. `raw_code` carrying an `app_script` `id` from another app must not run // against this Viewer app: the row carries its own modules and lock, which // would run under `vapp`'s identity. Here `999777` belongs to - // `u/test-user/private`, not to the targeted `vapp`, so the id lookup - // (scoped to the app) refuses it before any Viewer default applies. + // `u/test-user/private`, not to the targeted `vapp`, whose deployed version + // names no such row, so it is refused before any Viewer default applies. let resp = authed( client().post(format!("{base}/u/test-user/vapp")), "OPERATOR_TOKEN", @@ -336,12 +336,12 @@ async fn test_app_preview_authorization(db: Pool) -> anyhow::Result<() let status = resp.status(); let body = resp.text().await?; assert_eq!( - status, 401, + status, 409, "run-mode raw_code with another app's app_script id must be rejected against a Viewer app (got {status}): {body}" ); assert!( - body.contains("does not belong to app u/test-user/vapp"), - "rejection must be the app scoping of the app_script id, got: {body}" + body.contains("not part of the deployed version of app u/test-user/vapp"), + "rejection must be the deployed version check of the app_script id, got: {body}" ); // 12. Path confinement: the scope picker mints `apps:run:` / diff --git a/backend/tests/app_render_isolation_for_visitors.rs b/backend/tests/app_render_isolation_for_visitors.rs new file mode 100644 index 0000000000..b9da991e19 --- /dev/null +++ b/backend/tests/app_render_isolation_for_visitors.rs @@ -0,0 +1,91 @@ +//! An app its publisher left unsandboxed renders same-origin only for members of its +//! workspace; the embed-token response tells every other viewer to isolate it. +//! +//! Users from the `base` fixture: +//! test-user (admin, superadmin, token SECRET_TOKEN) +//! test-user-2 (member, token SECRET_TOKEN_2) + +use serde_json::json; +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +const APP_PATH: &str = "u/test-user/unsandboxed_app"; +const OUTSIDER_SUPERADMIN_TOKEN: &str = "OUTSIDER_SUPERADMIN"; + +async fn embed_sandbox(url: &str, token: Option<&str>) -> anyhow::Result { + let mut req = reqwest::Client::new().get(url); + if let Some(t) = token { + req = req.header("Authorization", format!("Bearer {t}")); + } + let resp = req.send().await?; + assert_eq!(resp.status(), 200, "{url}: {}", resp.text().await?); + let body: serde_json::Value = resp.json().await?; + Ok(body["sandbox"] + .as_bool() + .expect("embed-token response must say how to render")) +} + +#[sqlx::test(fixtures("base"))] +async fn unsandboxed_app_is_isolated_for_non_members(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let ws = format!("http://localhost:{port}/api/w/test-workspace"); + + // A superadmin of the instance who is not a member of the app's workspace. + sqlx::query( + "INSERT INTO password(email, password_hash, login_type, super_admin, verified, name) + VALUES ('outsider@windmill.dev', 'not-a-real-hash', 'password', true, true, 'Outsider')", + ) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO token(token_hash, token_prefix, token, email, label, super_admin) + VALUES (encode(sha256($1::bytea), 'hex'), 'OUTSIDER_S', $1, 'outsider@windmill.dev', 'session', true)", + ) + .bind(OUTSIDER_SUPERADMIN_TOKEN) + .execute(&db) + .await?; + + let resp = reqwest::Client::new() + .post(format!("{ws}/apps/create")) + .header("Authorization", "Bearer SECRET_TOKEN") + .json(&json!({ + "path": APP_PATH, + "summary": "Unsandboxed app", + "value": {}, + "policy": { "execution_mode": "anonymous", "triggerables": {}, "sandbox": false } + })) + .send() + .await?; + assert_eq!(resp.status(), 201, "{}", resp.text().await?); + let secret = reqwest::Client::new() + .get(format!("{ws}/apps/secret_of/{APP_PATH}")) + .header("Authorization", "Bearer SECRET_TOKEN") + .send() + .await? + .text() + .await?; + + let by_secret = format!("{ws}/apps_u/embed_token/{secret}"); + assert!(embed_sandbox(&by_secret, None).await?, "anonymous visitor"); + assert!( + embed_sandbox(&by_secret, Some(OUTSIDER_SUPERADMIN_TOKEN)).await?, + "superadmin outside the workspace" + ); + assert!( + !embed_sandbox(&by_secret, Some("SECRET_TOKEN_2")).await?, + "a member keeps the publisher's choice" + ); + + let by_path = format!("{ws}/apps/embed_token/p/{APP_PATH}"); + assert!( + embed_sandbox(&by_path, Some(OUTSIDER_SUPERADMIN_TOKEN)).await?, + "superadmin outside the workspace, in-workspace viewer" + ); + assert!( + !embed_sandbox(&by_path, Some("SECRET_TOKEN")).await?, + "a member keeps the publisher's choice, in-workspace viewer" + ); + Ok(()) +} diff --git a/backend/tests/app_run_mode_lock_strip.rs b/backend/tests/app_run_mode_lock_strip.rs index 77265f2bcd..32ff8e6e50 100644 --- a/backend/tests/app_run_mode_lock_strip.rs +++ b/backend/tests/app_run_mode_lock_strip.rs @@ -278,18 +278,43 @@ async fn test_app_script_run_derives_path(db: Pool) -> anyhow::Result< .fetch_one(&db) .await?; - let resp = authed( - client().post(format!("{ws}/apps_u/execute_component/{app_path}")), - "SECRET_TOKEN_2", + let run = || { + authed( + client().post(format!("{ws}/apps_u/execute_component/{app_path}")), + "SECRET_TOKEN_2", + ) + .json(&json!({ + "args": {}, + "component": "comp", + "id": script_id, + "raw_code": { "language": "python3", "content": "", "path": CALLER_PATH } + })) + .send() + }; + + // Before its lite value exists, the deployed version's full value says which rows it runs. + let resp = run().await?; + let status = resp.status(); + assert_eq!( + status, + 409, + "a row the deployed version does not name must not run: {}", + resp.text().await? + ); + sqlx::query( + "UPDATE app_version SET value = $2::jsonb::json + WHERE id = (SELECT versions[array_upper(versions, 1)] FROM app WHERE path = $1)", ) - .json(&json!({ - "args": {}, - "component": "comp", - "id": script_id, - "raw_code": { "language": "python3", "content": "", "path": CALLER_PATH } - })) - .send() + .bind(app_path) + .bind( + json!({ "grid": [{ "data": { "componentInput": { "runnable": { + "inlineScript": { "id": script_id, "language": "python3" } + } } } }] }), + ) + .execute(&db) .await?; + + let resp = run().await?; let status = resp.status(); let body = resp.text().await?; assert_eq!( @@ -390,7 +415,7 @@ async fn test_run_mode_id_less_code_with_lite(db: Pool) -> anyhow::Res let status = resp.status(); assert_eq!( status, - 401, + 409, "id-less code must not run as a non-SQL language: {}", resp.text().await? ); @@ -399,7 +424,7 @@ async fn test_run_mode_id_less_code_with_lite(db: Pool) -> anyhow::Res let status = resp.status(); assert_eq!( status, - 401, + 409, "a deployed row's code must not run id-less: {}", resp.text().await? ); diff --git a/backend/tests/app_s3_onbehalf.rs b/backend/tests/app_s3_onbehalf.rs index c11c94be1e..167713c012 100644 --- a/backend/tests/app_s3_onbehalf.rs +++ b/backend/tests/app_s3_onbehalf.rs @@ -360,7 +360,7 @@ async fn test_deployed_app_s3_presigned_bypasses_gate(db: Pool) -> any Ok(()) } -/// Seed a completed job whose result carries an s3 object. `app_trigger` sets the +/// Seed a completed job with `result`, which carries s3 objects. `app_trigger` sets the /// app-origination marker exactly as `execute_component` stamps it: `Some(app_path)` /// => `trigger_kind = 'app'` + `trigger = ` (an app-launched run); /// `None` => an ordinary direct `/jobs/run` (no app marker). `created_by` is the user @@ -369,9 +369,8 @@ async fn seed_completed_job( db: &Pool, created_by: &str, app_trigger: Option<&str>, - s3_key: &str, + result: serde_json::Value, ) -> anyhow::Result<()> { - let result = format!(r#"{{"s3":"{s3_key}"}}"#); sqlx::query( r#" WITH j AS ( @@ -437,10 +436,33 @@ async fn test_deployed_app_s3_onbehalf_flow_script_provenance( // Seed the produced-file jobs (all within the 3h window). The gate's `created_by` // filter uses "anonymous" for an unauthenticated caller. - seed_completed_job(&db, "anonymous", Some(FS_APP), OWN_KEY).await?; - seed_completed_job(&db, "test-user-2", Some(FS_APP), OTHER_CALLER_KEY).await?; - seed_completed_job(&db, "anonymous", Some(OTHER_APP), OTHER_APP_KEY).await?; - seed_completed_job(&db, "anonymous", None, FORGED_KEY).await?; + // A result that is a list of S3 objects, one of them in a secondary storage. + const LISTED_KEY: &str = "results/listed.csv"; + const SECONDARY_KEY: &str = "results/secondary.csv"; + + seed_completed_job(&db, "anonymous", Some(FS_APP), json!({ "s3": OWN_KEY })).await?; + seed_completed_job( + &db, + "test-user-2", + Some(FS_APP), + json!({ "s3": OTHER_CALLER_KEY }), + ) + .await?; + seed_completed_job( + &db, + "anonymous", + Some(OTHER_APP), + json!({ "s3": OTHER_APP_KEY }), + ) + .await?; + seed_completed_job(&db, "anonymous", None, json!({ "s3": FORGED_KEY })).await?; + seed_completed_job( + &db, + "anonymous", + Some(FS_APP), + json!([{ "s3": LISTED_KEY }, { "s3": SECONDARY_KEY, "storage": "secondary" }]), + ) + .await?; let denied = |body: &str| body.contains("is not accessible from this app"); // Anonymous GET (borrows `ws`, reusable across calls: the URL is built before the @@ -491,6 +513,26 @@ async fn test_deployed_app_s3_onbehalf_flow_script_provenance( "key produced by a different app must stay denied: {body}" ); + // Each object of a list result clears the gate, in the storage the result names only. + let body = anon_body(format!("download_s3_file/{FS_APP}?s3={LISTED_KEY}")).await; + assert!( + !denied(&body), + "a key from a list result must clear the gate: {body}" + ); + let body = anon_body(format!( + "download_s3_file/{FS_APP}?s3={SECONDARY_KEY}&storage=secondary" + )) + .await; + assert!( + !denied(&body), + "a key in its own storage must clear the gate: {body}" + ); + let body = anon_body(format!("download_s3_file/{FS_APP}?s3={SECONDARY_KEY}")).await; + assert!( + denied(&body), + "a key requested from another storage than its result's must stay denied: {body}" + ); + Ok(()) } diff --git a/backend/tests/autoscaling_count.rs b/backend/tests/autoscaling_count.rs new file mode 100644 index 0000000000..31bbb0c726 --- /dev/null +++ b/backend/tests/autoscaling_count.rs @@ -0,0 +1,136 @@ +//! The worker count autoscaling decides from, driven through `apply_all_autoscaling` with a +//! dry-run integration against planted `worker_ping` rows. + +#![cfg(all(feature = "enterprise", feature = "private"))] + +use sqlx::{Pool, Postgres}; +use windmill_autoscaling::apply_all_autoscaling; + +async fn setup(db: &Pool) -> anyhow::Result<()> { + let updated = sqlx::query( + r#"UPDATE config SET config = config || '{"autoscaling": {"enabled": true, "min_workers": 2, + "max_workers": 12, "integration": {"type": "dryrun"}}}'::jsonb + WHERE name = 'worker__default'"#, + ) + .execute(db) + .await? + .rows_affected(); + assert_eq!(updated, 1, "the default worker group config is seeded"); + Ok(()) +} + +async fn plant_workers(db: &Pool, n: i32, draining: bool) -> anyhow::Result<()> { + sqlx::query( + "INSERT INTO worker_ping (worker, worker_instance, worker_group, started_at, draining) + SELECT 'wk-' || $2::text || '-' || i, 'pod-' || $2::text || '-' || i, 'default', + now() - interval '1 hour', $2 + FROM generate_series(1, $1) AS i", + ) + .bind(n) + .bind(draining) + .execute(db) + .await?; + Ok(()) +} + +/// `apply_all_autoscaling` runs only for the holder of a 15s lock, so each tick backdates it. +async fn tick(db: &Pool) -> anyhow::Result<()> { + sqlx::query( + "INSERT INTO concurrency_locks (id, last_locked_at) VALUES ('autoscaling', now() - interval '1 hour') + ON CONFLICT (id) DO UPDATE SET last_locked_at = EXCLUDED.last_locked_at", + ) + .execute(db) + .await?; + apply_all_autoscaling(db).await +} + +async fn events(db: &Pool) -> anyhow::Result> { + Ok(sqlx::query_as( + "SELECT desired_workers, reason FROM autoscaling_event WHERE worker_group = 'default' ORDER BY id", + ) + .fetch_all(db) + .await?) +} + +#[sqlx::test(migrations = "./migrations")] +async fn draining_workers_are_not_counted(db: Pool) -> anyhow::Result<()> { + setup(&db).await?; + plant_workers(&db, 12, false).await?; + plant_workers(&db, 2, true).await?; + + tick(&db).await?; + + assert_eq!(events(&db).await?, vec![]); + Ok(()) +} + +#[sqlx::test(migrations = "./migrations")] +async fn above_max_applies_max_once_per_cooldown(db: Pool) -> anyhow::Result<()> { + setup(&db).await?; + plant_workers(&db, 14, false).await?; + + tick(&db).await?; + tick(&db).await?; + + let events = events(&db).await?; + assert_eq!(events.len(), 1, "{events:?}"); + assert_eq!(events[0].0, 12); + + sqlx::query("UPDATE autoscaling_event SET applied_at = applied_at - interval '10 minutes'") + .execute(&db) + .await?; + tick(&db).await?; + assert_eq!(self::events(&db).await?.len(), 2); + Ok(()) +} + +/// A group restarting in place marks every worker draining while its pods remain replicas. +#[sqlx::test(migrations = "./migrations")] +async fn restarting_group_is_not_scaled_below_last_applied(db: Pool) -> anyhow::Result<()> { + setup(&db).await?; + sqlx::query( + "INSERT INTO autoscaling_event (worker_group, event_type, desired_workers, reason) + VALUES ('default', 'scaleout', 10, 'planted')", + ) + .execute(&db) + .await?; + plant_workers(&db, 1, false).await?; + plant_workers(&db, 9, true).await?; + + tick(&db).await?; + assert_eq!(events(&db).await?.len(), 1); + + sqlx::query("UPDATE autoscaling_event SET applied_at = applied_at - interval '10 minutes'") + .execute(&db) + .await?; + tick(&db).await?; + let events = events(&db).await?; + assert_eq!(events.last().map(|e| e.0), Some(10), "{events:?}"); + Ok(()) +} + +/// Idle restarted workers beside ones still draining must not make one scale-in remove the +/// draining pods too. +#[sqlx::test(migrations = "./migrations")] +async fn partially_restarted_group_scales_in_one_step(db: Pool) -> anyhow::Result<()> { + setup(&db).await?; + sqlx::query( + "INSERT INTO autoscaling_event (worker_group, event_type, desired_workers, reason, applied_at) + VALUES ('default', 'scaleout', 10, 'planted', now() - interval '10 minutes')", + ) + .execute(&db) + .await?; + plant_workers(&db, 4, false).await?; + plant_workers(&db, 6, true).await?; + sqlx::query( + "UPDATE worker_ping SET occupancy_rate_15s = 0, occupancy_rate_5m = 0, occupancy_rate_30m = 0", + ) + .execute(&db) + .await?; + + tick(&db).await?; + + let events = events(&db).await?; + assert_eq!(events.last().map(|e| e.0), Some(8), "{events:?}"); + Ok(()) +} diff --git a/backend/tests/dedicated_workers.rs b/backend/tests/dedicated_workers.rs index fc4ff77bb3..c69bcc4563 100644 --- a/backend/tests/dedicated_workers.rs +++ b/backend/tests/dedicated_workers.rs @@ -313,10 +313,10 @@ mod dedicated_worker_tests { Ok(()) } - /// Test flow runners: a squashed for-loop spawns dedicated subprocesses. + /// A squashed for-loop runs each iteration as a regular job, not in a shared subprocess. #[sqlx::test(fixtures("base", "dedicated_flows"))] #[serial] - async fn test_dedicated_flow_runners(db: Pool) -> anyhow::Result<()> { + async fn test_squashed_loop_runs_iterations_as_jobs(db: Pool) -> anyhow::Result<()> { initialize_tracing().await; // Reset dedicated_workers in WORKER_CONFIG to avoid pollution from previous tests. { @@ -355,8 +355,17 @@ mod dedicated_worker_tests { // for-loop over [1, 2, 3], each * 10 = [10, 20, 30] assert_eq!(job.json_result().unwrap(), json!([10, 20, 30])); - // Verify the loop iterations ran on dedicated worker subprocesses - assert_ran_on_dedicated_worker(&db, job.id, "bun").await; + let in_subprocess: i64 = sqlx::query_scalar( + "WITH RECURSIVE t(id) AS ( + SELECT $1::uuid UNION SELECT j.id FROM v2_job j JOIN t ON j.parent_job = t.id + ) + SELECT count(*) FROM job_logs l JOIN t ON l.job_id = t.id + WHERE l.logs LIKE '%dedicated worker%'", + ) + .bind(job.id) + .fetch_one(&db) + .await?; + assert_eq!(in_subprocess, 0); Ok(()) } @@ -732,8 +741,7 @@ mod dedicated_worker_tests { Ok(()) } - /// Test a squashed for-loop with a bash step (unsupported for flow runners). - /// The bash step can't spawn a flow runner, so each iteration falls back to normal execution. + /// Test a squashed for-loop with a bash step. #[sqlx::test(fixtures("base", "dedicated_flows"))] #[serial] async fn test_dedicated_flow_runners_unsupported_lang( diff --git a/backend/tests/duplicate_session_cookie.rs b/backend/tests/duplicate_session_cookie.rs new file mode 100644 index 0000000000..8122e27b6d --- /dev/null +++ b/backend/tests/duplicate_session_cookie.rs @@ -0,0 +1,38 @@ +//! A browser can send two `token` cookies: this instance's, and one a parent-domain instance set +//! with `Domain=` (app.windmill.dev on `.windmill.dev`, seen from a tenant subdomain). Safari +//! sends the host's cookie first and Chrome last, so the request must authenticate on whichever +//! is a live session here, in either order. + +use reqwest::StatusCode; +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +#[sqlx::test(fixtures("base"))] +async fn test_duplicate_session_cookie_uses_the_live_one(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + + let server = ApiServer::start(db.clone()).await?; + let client = reqwest::Client::new(); + let url = format!( + "http://localhost:{}/api/workspaces/users", + server.addr.port() + ); + let status = |cookie: &'static str| { + let req = client.get(&url).header("Cookie", cookie); + async move { anyhow::Ok(req.send().await?.status()) } + }; + + assert_eq!( + status("token=FOREIGN_INSTANCE_TOKEN; token=SECRET_TOKEN").await?, + StatusCode::OK + ); + assert_eq!( + status("token=SECRET_TOKEN; token=FOREIGN_INSTANCE_TOKEN").await?, + StatusCode::OK + ); + assert_eq!( + status("token=FOREIGN_INSTANCE_TOKEN; token=OTHER_FOREIGN_TOKEN").await?, + StatusCode::UNAUTHORIZED + ); + Ok(()) +} diff --git a/backend/tests/flow_engine_parity.rs b/backend/tests/flow_engine_parity.rs index 08303f565f..2d43307daa 100644 --- a/backend/tests/flow_engine_parity.rs +++ b/backend/tests/flow_engine_parity.rs @@ -189,6 +189,7 @@ export function main() { parallel: false, squash: None, iteration_label: None, + failure_threshold: None, parallelism: None, modules: vec![flow_module( "c", @@ -533,6 +534,7 @@ export function main() { parallel: false, squash: None, iteration_label: None, + failure_threshold: None, parallelism: None, modules: vec![ // For each category, compute results using base_values @@ -983,6 +985,7 @@ export function main() { parallel: true, squash: None, iteration_label: None, + failure_threshold: None, parallelism: None, modules: vec![flow_module( "process", @@ -1901,6 +1904,7 @@ export function main() { parallel: false, squash: None, iteration_label: None, + failure_threshold: None, parallelism: None, modules: vec![ // Step b: generate inner items based on category @@ -2544,6 +2548,7 @@ export function main() { parallelism: None, squash: None, iteration_label: None, + failure_threshold: None, }, )], flow_env: Some(flow_env), @@ -3310,6 +3315,7 @@ export function main(i: number) { parallelism: None, squash: None, iteration_label: None, + failure_threshold: None, }, ); m.stop_after_all_iters_if = Some(windmill_common::flows::StopAfterIf { @@ -3412,6 +3418,7 @@ export function main(i: number) { parallelism: None, squash: None, iteration_label: None, + failure_threshold: None, }, ); m.stop_after_all_iters_if = Some(windmill_common::flows::StopAfterIf { diff --git a/backend/tests/http_route_read_only_token.rs b/backend/tests/http_route_read_only_token.rs new file mode 100644 index 0000000000..37510b8089 --- /dev/null +++ b/backend/tests/http_route_read_only_token.rs @@ -0,0 +1,55 @@ +//! `/api/r/*` resolves its token outside the `ApiAuthed` extractor, so it must refuse a +//! read-only token itself: calling a route runs its runnable as the route's owner. + +#![cfg(feature = "http_trigger")] + +use serde_json::json; +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +#[sqlx::test(fixtures("base", "hello"))] +async fn read_only_token_cannot_call_http_route(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + sqlx::query( + "INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin, workspace_id, read_only) + VALUES (encode(sha256('RO_TOKEN'::bytea), 'hex'), 'RO_TOKEN', 'RO_TOKEN', 'test@windmill.dev', + 'ro', false, 'test-workspace', true)", + ) + .execute(&db) + .await?; + let client = reqwest::Client::new(); + let resp = client + .post(format!( + "http://localhost:{port}/api/w/test-workspace/http_triggers/create" + )) + .bearer_auth("SECRET_TOKEN") + .json(&json!({ + "path": "u/test-user/route", + "script_path": "f/system/hello", + "is_flow": false, + "route_path": "ro", + "request_type": "async", + "authentication_method": "windmill", + "http_method": "post", + "is_static_website": false, + "workspaced_route": false, + })) + .send() + .await?; + assert!(resp.status().is_success(), "{}", resp.text().await?); + + let call = |token: &'static str| { + client + .post(format!("http://localhost:{port}/api/r/ro")) + .bearer_auth(token) + .json(&json!({})) + .send() + }; + let resp = call("RO_TOKEN").await?; + assert_eq!(resp.status(), 403, "{}", resp.text().await?); + let resp = call("SECRET_TOKEN").await?; + assert!(resp.status().is_success(), "{}", resp.text().await?); + Ok(()) +} diff --git a/backend/tests/jobs_cross_site_get.rs b/backend/tests/jobs_cross_site_get.rs index 5b6151c328..db602da9a6 100644 --- a/backend/tests/jobs_cross_site_get.rs +++ b/backend/tests/jobs_cross_site_get.rs @@ -14,12 +14,15 @@ //! exempting the parameter would let `?token=junk` reinstate the vector. //! //! This test pins down: -//! - both endpoints refuse a cross-site cookie GET to a Hub script (the core fix), whether -//! `Sec-Fetch-Site` says so or, with no such header (plain http), a cross-host `Referer`, +//! - both endpoints refuse a cookie GET to a Hub script from another site, same-site +//! included, whether `Sec-Fetch-Site` says so or, with no such header (plain http), a +//! cross-host `Referer`, //! - a junk `token` query parameter does not buy a pass, //! - the scope: the same request to a workspace script is not refused, +//! - a POST from another site does not authenticate on the cookie, but does on its own +//! `?token=`, //! - a Hub-script request with its own credential (bearer, or `?token=` and no cookie), or -//! sent as a POST, gets through. +//! sent as a same-origin POST, gets through. //! //! No runnable exists and no Hub is contacted. A request that gets past the guard fails as //! not-found on a workspace path, and for a Hub path on fetching it from a Hub pointed at a @@ -69,6 +72,11 @@ async fn test_cross_site_get_cannot_run_hub_scripts(db: Pool) -> anyho "Sec-Fetch-Site: cross-site", cookie_get(path).header("Sec-Fetch-Site", "cross-site"), ), + // A sibling subdomain gets the `SameSite=Lax` cookie on every request. + ( + "Sec-Fetch-Site: same-site", + cookie_get(path).header("Sec-Fetch-Site", "same-site"), + ), // Plain http gets no `Sec-Fetch-*` at all, so `Referer` is the only signal left. ( "cross-host Referer with no Sec-Fetch-Site", @@ -113,8 +121,32 @@ async fn test_cross_site_get_cannot_run_hub_scripts(db: Pool) -> anyho ); } - // ---- A Hub-script request that carries its own credential, or is a POST, gets through. + // ---- A POST from another site does not authenticate on the cookie. let hub = HUB_GETS[1]; + for (name, headers) in [ + ("same-site", &[("Sec-Fetch-Site", "same-site")][..]), + ( + "Origin on another host", + &[("Origin", "http://sibling.localhost")][..], + ), + ] { + let mut req = client + .post(format!("{base}/{hub}")) + .header("Cookie", "token=SECRET_TOKEN") + .json(&serde_json::json!({})); + for (k, v) in headers { + req = req.header(*k, *v); + } + let (status, body) = send(req).await?; + assert_eq!( + status, + StatusCode::FORBIDDEN, + "POST [{name}] must not use the cookie: {body}" + ); + } + + // ---- A Hub-script request that carries its own credential, or is a same-origin POST, + // gets through. let allowed = [ ( "cross-origin bearer token", @@ -130,11 +162,19 @@ async fn test_cross_site_get_cannot_run_hub_scripts(db: Pool) -> anyho .header("Sec-Fetch-Site", "cross-site"), ), ( - "POST with the cookie", + "same-origin POST with the cookie", client .post(format!("{base}/{hub}")) .header("Cookie", "token=SECRET_TOKEN") - .header("Sec-Fetch-Site", "cross-site") + .header("Sec-Fetch-Site", "same-origin") + .json(&serde_json::json!({})), + ), + ( + "same-site POST with ?token= next to the cookie", + client + .post(format!("{base}/{hub}?token=SECRET_TOKEN")) + .header("Cookie", "token=junk") + .header("Sec-Fetch-Site", "same-site") .json(&serde_json::json!({})), ), ]; diff --git a/backend/tests/jobs_read_auth.rs b/backend/tests/jobs_read_auth.rs index bffacfbaf0..e52530d63c 100644 --- a/backend/tests/jobs_read_auth.rs +++ b/backend/tests/jobs_read_auth.rs @@ -139,6 +139,10 @@ async fn test_single_job_read_authorization(db: Pool) -> anyhow::Resul "completed/get_result_maybe", format!("completed/get_result_maybe/{VICTIM}"), ), + ( + "completed/get_result_shape", + format!("completed/get_result_shape/{VICTIM}"), + ), ("get_args", format!("get_args/{VICTIM}")), ("get_logs", format!("get_logs/{VICTIM}")), ( @@ -1226,3 +1230,80 @@ async fn test_single_job_read_authorization(db: Pool) -> anyhow::Resul Ok(()) } + +/// `get_result_shape` outlines a result too large to send inline: the viewer draws one row per +/// listed element and reads each one through `get_result?json_path=.`, so the cap, +/// the element order and the path handling are what it relies on. +#[sqlx::test(fixtures("base"))] +async fn test_result_shape(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let job = "99999999-9999-9999-9999-999999999999"; + sqlx::query( + "INSERT INTO v2_job (id, workspace_id, created_by, permissioned_as, permissioned_as_email, + kind, script_lang, tag) + VALUES ($1::uuid, 'test-workspace', 'test-user', 'u/test-user', 'test@windmill.dev', + 'script', 'bun', 'bun')", + ) + .bind(job) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO v2_job_completed (id, workspace_id, duration_ms, status, result) + SELECT $1::uuid, 'test-workspace', 1, 'success'::job_status, jsonb_build_object( + 'render_all', + (SELECT jsonb_agg(CASE WHEN i = 1 THEN jsonb_build_object('png', 'aGVsbG8=') + ELSE jsonb_build_object('n', i) END ORDER BY i) + FROM generate_series(1, 105) AS i))", + ) + .bind(job) + .execute(&db) + .await?; + + let server = ApiServer::start(db.clone()).await?; + let base = format!( + "http://localhost:{}/api/w/test-workspace/jobs_u/completed/get_result_shape/{job}", + server.addr.port() + ); + let shape = |query: &'static str| { + let url = format!("{base}{query}"); + async move { + let resp = client() + .get(url) + .header("Authorization", "Bearer SECRET_TOKEN") + .send() + .await + .expect("request"); + (resp.status(), resp.text().await.expect("body")) + } + }; + + let (status, body) = shape("").await; + assert_eq!(status, 200, "{body}"); + let root: serde_json::Value = serde_json::from_str(&body)?; + assert_eq!(root["type"], "object"); + assert_eq!(root["keys"], serde_json::json!(["render_all"])); + assert!(root.get("items").is_none(), "{body}"); + + let (status, body) = shape("?json_path=render_all").await; + assert_eq!(status, 200, "{body}"); + let list: serde_json::Value = serde_json::from_str(&body)?; + assert_eq!(list["type"], "array"); + assert_eq!(list["item_count"], 105); + let items = list["items"].as_array().expect("items"); + assert_eq!(items.len(), 100); + assert_eq!(items[0]["keys"], serde_json::json!(["png"])); + assert_eq!(items[0]["length"], r#"{"png": "aGVsbG8="}"#.len()); + assert_eq!(items[1]["keys"], serde_json::json!(["n"])); + + let (status, body) = shape("?json_path=render_all.0").await; + assert_eq!(status, 200, "{body}"); + assert_eq!( + serde_json::from_str::(&body)?["keys"], + serde_json::json!(["png"]) + ); + + let (status, body) = shape("?json_path=missing").await; + assert_eq!(status, 404, "{body}"); + + Ok(()) +} diff --git a/backend/tests/mcp_header_var_refs.rs b/backend/tests/mcp_header_var_refs.rs index 270ae35449..1a4eec2d5f 100644 --- a/backend/tests/mcp_header_var_refs.rs +++ b/backend/tests/mcp_header_var_refs.rs @@ -91,7 +91,7 @@ async fn test_mcp_header_var_ref_requires_variable_scope(db: Pool) -> let server = ApiServer::start(db.clone()).await?; let resp = reqwest::Client::new() - .get(format!( + .post(format!( "http://localhost:{}/api/w/test-workspace/resources/mcp_tools/u/test-user/mcp", server.addr.port() )) @@ -127,7 +127,7 @@ async fn test_mcp_header_var_ref_requires_variable_scope(db: Pool) -> .execute(&db) .await?; let resp = reqwest::Client::new() - .get(format!( + .post(format!( "http://localhost:{}/api/w/test-workspace/resources/mcp_tools/u/test-user/mcp", server.addr.port() )) diff --git a/backend/tests/mcp_resource_authz.rs b/backend/tests/mcp_resource_authz.rs index 6ccf5f4f2d..f1b7079445 100644 --- a/backend/tests/mcp_resource_authz.rs +++ b/backend/tests/mcp_resource_authz.rs @@ -74,7 +74,7 @@ async fn test_mcp_resource_not_loaded_without_authorization( ) .await; assert!( - msg.contains("don't have access"), + msg.contains("nothing grants you access"), "denial should come from the resource-RLS gate, not a connection error: {msg}" ); // An unauthorized caller must be blocked before MCP client creation, so no @@ -99,7 +99,7 @@ async fn test_mcp_resource_not_loaded_without_authorization( ) .await; assert!( - !msg.contains("don't have access"), + !msg.contains("nothing grants you access"), "admin must clear the resource-RLS gate, not be denied: {msg}" ); assert!( diff --git a/backend/tests/mcp_token_exfil.rs b/backend/tests/mcp_token_exfil.rs index 1d36ba9546..d6a6cfae61 100644 --- a/backend/tests/mcp_token_exfil.rs +++ b/backend/tests/mcp_token_exfil.rs @@ -1,6 +1,6 @@ //! Regression test for the MCP token-exfiltration vulnerability. //! -//! `GET /api/w/{w}/resources/mcp_tools/{path}` builds an MCP client from a +//! `POST /api/w/{w}/resources/mcp_tools/{path}` builds an MCP client from a //! resource whose `token` field is a `$var:` reference. Before the fix the token //! was resolved with `get_secret_value_as_admin` on the bare DB pool — no RLS, //! no audit — so any workspace member who could read an MCP *resource* could @@ -38,9 +38,9 @@ fn client() -> reqwest::Client { reqwest::Client::new() } -async fn get(base: &str, path: &str, token: &str) -> (reqwest::StatusCode, String) { +async fn list_tools(base: &str, path: &str, token: &str) -> (reqwest::StatusCode, String) { let resp = client() - .get(format!("{base}/{path}")) + .post(format!("{base}/{path}")) .header("Authorization", format!("Bearer {token}")) .send() .await @@ -100,7 +100,7 @@ async fn test_mcp_token_not_exfiltrated(db: Pool) -> anyhow::Result<() // able to resolve the locked secret. They are denied (401) at the // variable-RLS gate, before any MCP connection is attempted, and the // secret never appears in the response. - let (status, body) = get(&base, path, "SECRET_TOKEN_3").await; + let (status, body) = list_tools(&base, path, "SECRET_TOKEN_3").await; assert_eq!( status, reqwest::StatusCode::UNAUTHORIZED, @@ -111,7 +111,7 @@ async fn test_mcp_token_not_exfiltrated(db: Pool) -> anyhow::Result<() "the locked secret must never leak to the developer: {body}" ); assert!( - body.contains("don't have access"), + body.contains("nothing grants you access"), "denial should come from the variable-RLS gate, not a connection error: {body}" ); // Pre-fix, the token was decrypted as admin and the handler proceeded to the @@ -125,7 +125,7 @@ async fn test_mcp_token_not_exfiltrated(db: Pool) -> anyhow::Result<() // resolves and the request only fails later at the connect/SSRF step. // A different failure mode (not 401, reaches the connection) proves the // legitimate read still works. - let (status, body) = get(&base, path, "SECRET_TOKEN").await; + let (status, body) = list_tools(&base, path, "SECRET_TOKEN").await; assert_ne!( status, reqwest::StatusCode::UNAUTHORIZED, @@ -161,7 +161,7 @@ async fn test_mcp_call_tool_token_not_exfiltrated(db: Pool) -> anyhow: "the locked secret must never leak to the developer: {resp}" ); assert!( - resp.contains("don't have access"), + resp.contains("nothing grants you access"), "denial should come from the variable-RLS gate, not a connection error: {resp}" ); assert!( diff --git a/backend/tests/perpetual_deploy_restart.rs b/backend/tests/perpetual_deploy_restart.rs index 6f9e82e5c6..1dc7fbb4f4 100644 --- a/backend/tests/perpetual_deploy_restart.rs +++ b/backend/tests/perpetual_deploy_restart.rs @@ -202,6 +202,49 @@ async fn a_replacement_runs_as_the_identity_the_deployed_version_names( Ok(()) } +/// The identity an earlier version names stays with that version's code: a version deployed by +/// someone else without one does not take it over. +#[sqlx::test(fixtures("base"))] +async fn a_run_keeps_its_version_when_the_deployed_one_drops_its_identity( + db: Pool, +) -> anyhow::Result<()> { + let path = "u/test-user/named-identity"; + insert_version(&db, path, 801, 60.0, true).await?; + sqlx::query( + "UPDATE script SET on_behalf_of = 'u/test-user' WHERE hash = 801 AND workspace_id = $1", + ) + .bind(W_ID) + .execute(&db) + .await?; + let running = start_run(&db, path, 801).await?; + insert_version(&db, path, 802, 0.0, true).await?; + + restart_perpetual_runs_on_new_version(&db, W_ID, path, "test-user-2").await; + + let queued: Vec<(Uuid, Option)> = sqlx::query_as( + "SELECT q.id, q.canceled_reason FROM v2_job_queue q JOIN v2_job j USING (id) \ + WHERE j.workspace_id = $1 AND j.runnable_path = $2", + ) + .bind(W_ID) + .bind(path) + .fetch_all(&db) + .await?; + assert_eq!(queued, vec![(running, None)]); + + restart_perpetual_runs_on_new_version(&db, W_ID, path, "test-user").await; + + let hash: i64 = sqlx::query_scalar( + "SELECT j.runnable_id FROM v2_job j JOIN v2_job_queue q USING (id) \ + WHERE j.workspace_id = $1 AND j.runnable_path = $2 AND q.canceled_by IS NULL", + ) + .bind(W_ID) + .bind(path) + .fetch_one(&db) + .await?; + assert_eq!(hash, 802, "a deploy by that identity itself moves the run"); + Ok(()) +} + #[sqlx::test(fixtures("base"))] async fn a_run_stays_on_its_version_when_it_may_not_use_the_deployed_tag( db: Pool, diff --git a/backend/tests/postgres_trigger_scope.rs b/backend/tests/postgres_trigger_scope.rs index 9e7d8a665b..f87a705dad 100644 --- a/backend/tests/postgres_trigger_scope.rs +++ b/backend/tests/postgres_trigger_scope.rs @@ -28,6 +28,9 @@ fn scoped_authed(scopes: Vec<&str>) -> ApiAuthed { credential_expiry: None, mcp_client: None, capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), + allowed_ips: None, + admin_withheld: false, + super_admin_withheld: false, } } diff --git a/backend/tests/protection_rules.rs b/backend/tests/protection_rules.rs index bb9ef29fa2..8b897f35f5 100644 --- a/backend/tests/protection_rules.rs +++ b/backend/tests/protection_rules.rs @@ -801,3 +801,83 @@ async fn test_require_isolated_forks(db: Pool) -> anyhow::Result<()> { Ok(()) } + +#[sqlx::test(fixtures("base"))] +async fn test_require_sso(db: Pool) -> anyhow::Result<()> { + sqlx::raw_sql( + "INSERT INTO workspace (id, name, owner) VALUES ('sso-ws', 'sso-ws', 'test-user'); + INSERT INTO workspace_settings (workspace_id) VALUES ('sso-ws'); + INSERT INTO group_ (workspace_id, name, summary, extra_perms) VALUES + ('sso-ws', 'all', 'All users', '{}'); + INSERT INTO usr (workspace_id, email, username, is_admin, role) VALUES + ('sso-ws', 'test@windmill.dev', 'test-user', true, 'Admin'); + INSERT INTO password (email, login_type, verified, username) VALUES + ('sso@windmill.dev', 'google', true, 'sso-user'), + ('pw@windmill.dev', 'password', true, 'pw-user'), + ('pw-bypass@windmill.dev', 'password', true, 'pw-bypass')", + ) + .execute(&db) + .await?; + + let server = ApiServer::start(db.clone()).await?; + let api = format!("http://localhost:{}/api", server.addr.port()); + let post = |path: String, body: serde_json::Value| { + authed(client().post(format!("{api}{path}")), "SECRET_TOKEN").json(&body) + }; + let add = |email: &str| { + post( + "/w/sso-ws/workspaces/add_user".to_string(), + json!({"email": email, "is_admin": false, "operator": false}), + ) + }; + + let resp = post( + "/w/sso-ws/workspaces/protection_rules".to_string(), + json!({"name": "sso", "rules": ["RequireSso"], "bypass_groups": [], "bypass_users": ["pw-bypass"]}), + ) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + + let resp = add("pw@windmill.dev").send().await?; + let status = resp.status(); + let text = resp.text().await?; + assert_eq!(status, 400, "a password account must not join: {text}"); + assert!(text.contains("requires SSO"), "{text}"); + + for email in ["sso@windmill.dev", "pw-bypass@windmill.dev"] { + let resp = add(email).send().await?; + assert_eq!(resp.status(), 201, "{email}: {}", resp.text().await?); + } + + let to_password = |email: &str| { + post( + format!("/users/set_login_type/{email}"), + json!({"login_type": "password"}), + ) + }; + let resp = to_password("sso@windmill.dev").send().await?; + assert_eq!(resp.status(), 400, "{}", resp.text().await?); + let login_type: String = + sqlx::query_scalar("SELECT login_type FROM password WHERE email = 'sso@windmill.dev'") + .fetch_one(&db) + .await?; + assert_eq!(login_type, "google"); + + // A bypasser is not held by the rule. + let resp = to_password("pw-bypass@windmill.dev").send().await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + + // Every new member is in `all`, so bypassing it admits anyone. + let resp = post( + "/w/sso-ws/workspaces/protection_rules/sso".to_string(), + json!({"name": "sso", "rules": ["RequireSso"], "bypass_groups": ["all"], "bypass_users": []}), + ) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + let resp = add("pw@windmill.dev").send().await?; + assert_eq!(resp.status(), 201, "{}", resp.text().await?); + + Ok(()) +} diff --git a/backend/tests/reserved_control_args.rs b/backend/tests/reserved_control_args.rs index ed0fa6d002..d4912ed669 100644 --- a/backend/tests/reserved_control_args.rs +++ b/backend/tests/reserved_control_args.rs @@ -92,6 +92,9 @@ fn trigger_authed() -> windmill_api_auth::ApiAuthed { credential_expiry: None, mcp_client: None, capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), + allowed_ips: None, + admin_withheld: false, + super_admin_withheld: false, } } diff --git a/backend/tests/token_allowed_ips.rs b/backend/tests/token_allowed_ips.rs new file mode 100644 index 0000000000..0a95348d99 --- /dev/null +++ b/backend/tests/token_allowed_ips.rs @@ -0,0 +1,83 @@ +//! A token restricted to `allowed_ips` works only from those networks, and cannot mint a +//! credential that works from anywhere else. Setting a list is EE-only. +#![cfg(all(feature = "enterprise", feature = "private"))] + +use sqlx::{Pool, Postgres}; + +use windmill_test_utils::*; + +#[sqlx::test(fixtures("base"))] +async fn test_token_allowed_ips(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base = format!("http://localhost:{}/api/users", server.addr.port()); + let client = reqwest::Client::new(); + + for (token, nets) in [ + ("RESTRICTED_TOKEN", "{10.9.9.0/24}"), + ("LOOPBACK_TOKEN", "{127.0.0.1/32,::1/128}"), + ] { + sqlx::query( + "INSERT INTO token (token_hash, token_prefix, email, label, super_admin, allowed_ips) + VALUES (encode(sha256($1::bytea), 'hex'), substr($1, 1, 10), 'test@windmill.dev', + 'ci', false, $2::cidr[])", + ) + .bind(token) + .bind(nets) + .execute(&db) + .await?; + } + + // The test client connects from loopback, a trusted proxy by default, so + // X-Forwarded-For stands in for a client on another network. + let whoami = |token: &'static str, from: Option<&'static str>| { + let req = client.get(format!("{base}/whoami")).bearer_auth(token); + let req = match from { + Some(ip) => req.header("X-Forwarded-For", ip), + None => req, + }; + req.send() + }; + assert_eq!(whoami("RESTRICTED_TOKEN", None).await?.status(), 401); + assert_eq!( + whoami("RESTRICTED_TOKEN", Some("10.9.9.5")).await?.status(), + 200 + ); + // The identity is cached now; the address is still checked. + assert_eq!( + whoami("RESTRICTED_TOKEN", Some("8.8.8.8")).await?.status(), + 401 + ); + assert_eq!(whoami("LOOPBACK_TOKEN", None).await?.status(), 200); + assert_eq!( + whoami("LOOPBACK_TOKEN", Some("10.9.9.5")).await?.status(), + 401 + ); + + let create = |body: serde_json::Value| { + client + .post(format!("{base}/tokens/create")) + .bearer_auth("RESTRICTED_TOKEN") + .header("X-Forwarded-For", "10.9.9.5") + .json(&body) + .send() + }; + let resp = create(serde_json::json!({ "label": "child" })).await?; + assert_eq!(resp.status(), 201, "{}", resp.text().await?); + let inherited: Vec = + sqlx::query_scalar("SELECT unnest(allowed_ips)::text FROM token WHERE label = 'child'") + .fetch_all(&db) + .await?; + assert_eq!(inherited, vec!["10.9.9.0/24"]); + let resp = create(serde_json::json!({ "label": "wide", "allowed_ips": ["0.0.0.0/0"] })).await?; + assert_eq!(resp.status(), 403); + + let resp = client + .get(format!("{base}/refresh_token")) + .bearer_auth("RESTRICTED_TOKEN") + .header("X-Forwarded-For", "10.9.9.5") + .send() + .await?; + assert_eq!(resp.status(), 401); + Ok(()) +} diff --git a/backend/tests/trigger_listener_queries.rs b/backend/tests/trigger_listener_queries.rs index c2392202a8..72a9956347 100644 --- a/backend/tests/trigger_listener_queries.rs +++ b/backend/tests/trigger_listener_queries.rs @@ -181,6 +181,9 @@ fn make_authed() -> windmill_api_auth::ApiAuthed { credential_expiry: None, mcp_client: None, capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), + allowed_ips: None, + admin_withheld: false, + super_admin_withheld: false, } } diff --git a/backend/tests/trigger_run_scope.rs b/backend/tests/trigger_run_scope.rs new file mode 100644 index 0000000000..d11c07b78b --- /dev/null +++ b/backend/tests/trigger_run_scope.rs @@ -0,0 +1,83 @@ +//! A token scoped to one folder's schedules or triggers may bind them only to runnables it could +//! run itself: what they name later runs as the owner, with no token scopes left to check. + +use serde_json::{json, Value}; +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +#[sqlx::test(fixtures("base"))] +async fn a_save_needs_run_scope_on_what_it_names(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + sqlx::raw_sql( + r#"INSERT INTO folder(workspace_id, name, display_name, owners, extra_perms) + VALUES ('test-workspace', 'a', 'a', '{}', '{}'), ('test-workspace', 'b', 'b', '{}', '{}'); + INSERT INTO token(token_hash, token_prefix, token, email, label, scopes) VALUES + (encode(sha256('WRITE_ONLY'::bytea), 'hex'), 'WRITE_ONLY', 'WRITE_ONLY', + 'test@windmill.dev', 'w', '{schedules:write:f/a/*,http_triggers:write:f/a/*}'), + (encode(sha256('WRITE_RUN'::bytea), 'hex'), 'WRITE_RUN_', 'WRITE_RUN', + 'test@windmill.dev', 'wr', + '{schedules:write:f/a/*,http_triggers:write:f/a/*,jobs:run:scripts:f/b/*}');"#, + ) + .execute(&db) + .await?; + let server = ApiServer::start(db.clone()).await?; + let ws = format!( + "http://localhost:{}/api/w/test-workspace", + server.addr.port() + ); + let client = reqwest::Client::new(); + let send = async |token: &str, route: &str, body: Value| { + let resp = client + .post(format!("{ws}/{route}")) + .bearer_auth(token) + .json(&body) + .send() + .await + .unwrap(); + (resp.status().as_u16(), resp.text().await.unwrap()) + }; + + // (route, body, the path the write-only token is refused on) + #[allow(unused_mut)] + let mut saves: Vec<(&str, Value, &str)> = vec![ + ( + "schedules/create", + json!({"path": "f/a/sched", "schedule": "0 0 0 * * *", "timezone": "UTC", + "script_path": "f/b/x", "is_flow": false, "enabled": false}), + "f/b/x", + ), + ( + "schedules/create", + json!({"path": "f/a/sched_handler", "schedule": "0 0 0 * * *", "timezone": "UTC", + "script_path": "f/b/x", "is_flow": false, "enabled": false, + "on_failure": "script/f/b/y"}), + "f/b/y", + ), + ]; + #[cfg(feature = "http_trigger")] + saves.push(( + "http_triggers/create", + json!({"path": "f/a/route", "script_path": "f/b/x", "is_flow": false, + "mode": "disabled", "route_path": "a_route", "request_type": "async", + "authentication_method": "none", "http_method": "post", + "is_static_website": false, "workspaced_route": true, "wrap_body": false, + "raw_string": false}), + "f/b/x", + )); + + for (route, body, refused) in saves { + let (s, b) = send("WRITE_ONLY", route, body.clone()).await; + assert_eq!(s, 403, "{route} {body}: {b}"); + assert!(b.contains(&format!("jobs:run:scripts:{refused}")), "{b}"); + let (s, b) = send("WRITE_RUN", route, body.clone()).await; + assert!(s < 300, "{route} {body}: {b}"); + } + + // An edit sets the stored target's args, so it is held to the same scope. + let edit = json!({"schedule": "0 0 1 * * *", "timezone": "UTC", "args": {"x": 1}}); + let (s, b) = send("WRITE_ONLY", "schedules/update/f/a/sched", edit.clone()).await; + assert_eq!(s, 403, "{b}"); + let (s, b) = send("WRITE_RUN", "schedules/update/f/a/sched", edit).await; + assert!(s < 300, "{b}"); + Ok(()) +} diff --git a/backend/tests/untrusted_interpolation.rs b/backend/tests/untrusted_interpolation.rs index 12df3ab790..3b3e11158c 100644 --- a/backend/tests/untrusted_interpolation.rs +++ b/backend/tests/untrusted_interpolation.rs @@ -90,7 +90,7 @@ async fn run(db: &Pool, port: u16, id: Uuid) -> Value { fn assert_omitted(v: &Value) { let s = v.as_str().unwrap_or_default(); assert!( - s.starts_with("The following variable has been omitted for security reasons"), + s.starts_with("The following variable reference was not resolved"), "{v}" ); } diff --git a/backend/tests/volume_tests.rs b/backend/tests/volume_tests.rs index 9584cb1ae0..a46bb5b746 100644 --- a/backend/tests/volume_tests.rs +++ b/backend/tests/volume_tests.rs @@ -518,11 +518,12 @@ fn test_volume_nsjail_mount() { fn test_sync_stats_default() { use windmill_worker_volumes::SyncStats; - let stats = SyncStats { new_size_bytes: 0, file_count: 0, uploaded: 0, skipped: 0 }; + let stats = SyncStats { new_size_bytes: 0, file_count: 0, uploaded: 0, skipped: 0, deleted: 0 }; assert_eq!(stats.new_size_bytes, 0); assert_eq!(stats.file_count, 0); assert_eq!(stats.uploaded, 0); assert_eq!(stats.skipped, 0); + assert_eq!(stats.deleted, 0); } #[test] diff --git a/backend/tests/wm_token_confinement.rs b/backend/tests/wm_token_confinement.rs index 6b995115c2..dd70ac8e13 100644 --- a/backend/tests/wm_token_confinement.rs +++ b/backend/tests/wm_token_confinement.rs @@ -1131,6 +1131,9 @@ async fn test_privilege_gates_reject_a_job_token_directly( credential_expiry: None, mcp_client: None, capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), + allowed_ips: None, + admin_withheld: false, + super_admin_withheld: false, } } @@ -1229,3 +1232,42 @@ async fn test_privilege_gates_reject_a_job_token_directly( Ok(()) } + +/// A database source named by a `$res:` path is held to the token's resource scopes like any +/// other read of that resource, the instance database included, even for a token carrying its +/// owner's superadmin rights. +#[sqlx::test(fixtures("preserve_on_behalf_of"))] +async fn test_pg_source_is_held_to_resource_scopes(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let base = format!("http://localhost:{port}/api"); + + let resp = authed( + client().post(format!("{base}/users/tokens/create")), + "SECRET_TOKEN", + ) + .json(&json!({ + "label": "scoped", + "scopes": ["workspaces:write"], + "workspace_id": "test-workspace", + "super_admin": true, + })) + .send() + .await?; + assert_eq!(resp.status(), 201); + let scoped = resp.text().await?; + + let resp = authed( + client().post(format!( + "{base}/w/test-workspace/workspaces/get_datatable_full_schema" + )), + &scoped, + ) + .json(&json!({ "source": "$res:CUSTOM_INSTANCE_DB/windmill" })) + .send() + .await?; + assert_eq!(resp.status(), 403, "{}", resp.text().await?); + + Ok(()) +} diff --git a/backend/tests/worker.rs b/backend/tests/worker.rs index d53c4050fe..5a01b26cf1 100644 --- a/backend/tests/worker.rs +++ b/backend/tests/worker.rs @@ -285,6 +285,7 @@ async fn test_bun_flow(db: Pool) -> anyhow::Result<()> { parallel: false, squash: None, iteration_label: None, + failure_threshold: None, parallelism: None, modules: vec![FlowModule { id: "c".to_string(), @@ -642,6 +643,7 @@ async fn test_bun_flow_same_worker(db: Pool) -> anyhow::Result<()> { parallel: false, squash: None, iteration_label: None, + failure_threshold: None, parallelism: None, modules: vec![ FlowModule { @@ -5415,6 +5417,155 @@ async fn test_failure_module_recover_inside_loop(db: Pool) -> anyhow:: Ok(()) } +/// A loop skipping failures fails once `failure_threshold` iterations have failed: a sequential +/// loop runs no further iteration, a parallel one cancels the iterations not started yet. An error +/// handler recovering the failed iterations does not lift the threshold. +#[cfg(feature = "deno_core")] +#[sqlx::test(fixtures("base"))] +async fn test_loop_failure_threshold(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + let run = |parallel: bool, recovering_handler: bool| { + // Recovered, every iteration ends as a success job, so the loop fails on the threshold + // alone only if it is reached on the last iteration. + let items = if recovering_handler { + json!([1, 2]) + } else { + json!([1, 2, 3, 4, 5]) + }; + let mut flow = json!({ + "modules": [{ + "id": "loop", + "value": { + "type": "forloopflow", + "iterator": { "type": "static", "value": items }, + "skip_failures": true, + "failure_threshold": 2, + "parallel": parallel, + "parallelism": { "type": "static", "value": 1 }, + "modules": [{ + "id": "a", + "value": { + "input_transforms": {}, + "type": "rawscript", + "language": "bun", + "content": "export function main() { throw new Error('boom'); }", + }, + }], + }, + }, { + "id": "b", + "value": { + "input_transforms": {}, + "type": "rawscript", + "language": "bun", + "content": "export function main() { return { ran_b: true } }", + }, + }], + }); + if recovering_handler { + flow["failure_module"] = json!({ + "value": { + "input_transforms": { "error": { "type": "javascript", "expr": "error" } }, + "type": "rawscript", + "language": "bun", + "content": "export function main(error: any) { \ + return { handled: error.name, recover: error.name !== 'FailureThresholdReached' } }", + }, + }); + } + let flow: FlowValue = serde_json::from_value(flow).unwrap(); + RunJob::from(JobPayload::RawFlow { value: flow, path: None, restarted_from: None }) + .run_until_complete(&db, false, port) + }; + let iteration_statuses = |flow: Uuid| { + sqlx::query_scalar::<_, String>( + "SELECT c.status::text FROM v2_job_completed c JOIN v2_job j USING (id) + WHERE j.parent_job = $1 ORDER BY c.status::text", + ) + .bind(flow) + .fetch_all(&db) + }; + + let sequential = run(false, false).await; + let sequential_iterations = iteration_statuses(sequential.id).await?; + let parallel = run(true, false).await; + let parallel_iterations = iteration_statuses(parallel.id).await?; + let recovered = run(true, true).await; + let recovered_iterations = iteration_statuses(recovered.id).await?; + // A while loop with no stop condition ends only on its threshold, here an expression. + let while_flow: FlowValue = serde_json::from_value(json!({ + "modules": [{ + "id": "loop", + "value": { + "type": "whileloopflow", + "skip_failures": true, + "failure_threshold": { "type": "javascript", "expr": "1 + 2" }, + "modules": [{ + "id": "a", + "value": { + "input_transforms": {}, + "type": "rawscript", + "language": "bun", + "content": "export function main() { throw new Error('boom'); }", + }, + }], + }, + }], + })) + .unwrap(); + let while_loop = + RunJob::from(JobPayload::RawFlow { value: while_flow, path: None, restarted_from: None }) + .run_until_complete(&db, false, port) + .await; + let while_iterations = iteration_statuses(while_loop.id).await?; + // A percentage of an empty list is 0, which an empty loop never evaluates. + let empty_flow: FlowValue = serde_json::from_value(json!({ + "modules": [{ + "id": "loop", + "value": { + "type": "forloopflow", + "iterator": { "type": "static", "value": [] }, + "skip_failures": true, + "failure_threshold": { "type": "javascript", "expr": "Math.ceil([].length * 0.1)" }, + "modules": [], + }, + }], + })) + .unwrap(); + let empty_loop = + RunJob::from(JobPayload::RawFlow { value: empty_flow, path: None, restarted_from: None }) + .run_until_complete(&db, false, port) + .await; + server.close().await.unwrap(); + assert!(empty_loop.success, "{:?}", empty_loop.json_result()); + + for job in [&sequential, ¶llel, &while_loop] { + assert!(!job.success, "reaching the threshold must fail the flow"); + assert_eq!( + job.json_result().unwrap()["error"]["name"], + "FailureThresholdReached" + ); + } + assert_eq!(sequential_iterations, ["failure", "failure"]); + assert_eq!(while_iterations, ["failure", "failure", "failure"]); + assert_eq!( + parallel_iterations, + ["canceled", "canceled", "canceled", "failure", "failure"] + ); + // Both iterations and the handler of the threshold error. + assert_eq!(recovered_iterations, ["success", "success", "success"]); + assert!(!recovered.success, "recovered iterations still count"); + assert_eq!( + recovered.json_result().unwrap()["handled"], + "FailureThresholdReached", + "the handler must see the threshold error and the step after the loop must not run" + ); + Ok(()) +} + #[cfg(feature = "python")] #[sqlx::test(fixtures("base"))] async fn test_flow_lock_all(db: Pool) -> anyhow::Result<()> { diff --git a/backend/tests/workspace_encryption_key_scope.rs b/backend/tests/workspace_encryption_key_scope.rs index cef0fde598..1be1874ee5 100644 --- a/backend/tests/workspace_encryption_key_scope.rs +++ b/backend/tests/workspace_encryption_key_scope.rs @@ -20,13 +20,14 @@ fn authed(builder: reqwest::RequestBuilder, token: &str) -> reqwest::RequestBuil builder.header("Authorization", format!("Bearer {}", token)) } -/// Mint an API token for test-user (a workspace admin) restricted to `scopes`. +/// Mint an API token for test-user (a workspace admin and superadmin), carrying those rights, +/// restricted to `scopes`. async fn mint_scoped_token(port: u16, scopes: Vec<&str>) -> anyhow::Result { let resp = authed( client().post(format!("http://localhost:{port}/api/users/tokens/create")), ADMIN_TOKEN, ) - .json(&json!({ "label": "scoped", "scopes": scopes, "workspace_id": "test-workspace" })) + .json(&json!({ "label": "scoped", "scopes": scopes, "workspace_id": "test-workspace", "admin": true, "super_admin": true })) .send() .await?; assert_eq!(resp.status(), 201, "mint scoped token"); diff --git a/backend/tests/ws_specific.rs b/backend/tests/ws_specific.rs index 322de598b7..98a42d29b0 100644 --- a/backend/tests/ws_specific.rs +++ b/backend/tests/ws_specific.rs @@ -647,3 +647,102 @@ async fn test_bulk_delete_follows_what_rls_deleted(db: Pool) -> anyhow Ok(()) } + +/// A variable and a resource at the same path are deleted and renamed together, so a token +/// scoped to one kind must not move or delete the other through that pair. +#[sqlx::test(fixtures("ws_specific"))] +async fn test_scoped_token_needs_both_halves_of_a_linked_pair( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let base = format!("http://localhost:{port}/api/w/test-workspace"); + let path = "u/test-user/pair"; + + for (kind, body) in [ + ( + "variables", + json!({ "path": path, "value": "v", "is_secret": false, "description": "" }), + ), + ( + "resources", + json!({ "path": path, "value": { "a": 1 }, "resource_type": "object" }), + ), + ] { + let resp = authed( + client().post(format!("{base}/{kind}/create")), + "SECRET_TOKEN", + ) + .json(&body) + .send() + .await?; + assert_eq!(resp.status(), 201, "create {kind}: {}", resp.text().await?); + } + + let var_only = mint_scoped_token(port, vec!["variables:write:u/test-user/*"]).await?; + let res_only = mint_scoped_token(port, vec!["resources:write:u/test-user/*"]).await?; + let attempts = [ + ( + &var_only, + client().delete(format!("{base}/variables/delete/{path}")), + json!(null), + ), + ( + &var_only, + client().delete(format!("{base}/variables/delete_bulk")), + json!({ "paths": [path] }), + ), + ( + &var_only, + client().post(format!("{base}/variables/update/{path}")), + json!({ "path": "u/test-user/pair2" }), + ), + ( + &res_only, + client().post(format!("{base}/resources/update/{path}")), + json!({ "path": "u/test-user/pair2" }), + ), + ]; + for (token, req, body) in attempts { + let req = if body.is_null() { req } else { req.json(&body) }; + let resp = authed(req, token).send().await?; + assert_eq!(resp.status(), 403, "{}", resp.text().await?); + } + + for table in ["variable", "resource"] { + let n: i64 = sqlx::query_scalar(&format!( + "SELECT COUNT(*) FROM {table} WHERE workspace_id = 'test-workspace' AND path = $1" + )) + .bind(path) + .fetch_one(&db) + .await?; + assert_eq!(n, 1, "the {table} must stay where it was"); + } + + // A token holding both scopes still renames the pair. + let both = mint_scoped_token( + port, + vec![ + "variables:write:u/test-user/*", + "resources:write:u/test-user/*", + ], + ) + .await?; + let resp = authed( + client().post(format!("{base}/variables/update/{path}")), + &both, + ) + .json(&json!({ "path": "u/test-user/pair2" })) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + let moved: i64 = sqlx::query_scalar( + "SELECT COUNT(*) FROM resource WHERE workspace_id = 'test-workspace' AND path = 'u/test-user/pair2'", + ) + .fetch_one(&db) + .await?; + assert_eq!(moved, 1); + + Ok(()) +} diff --git a/backend/windmill-api-assets/tests/dbt_pinned_graph.rs b/backend/windmill-api-assets/tests/dbt_pinned_graph.rs index eaa531dc4b..e607899e20 100644 --- a/backend/windmill-api-assets/tests/dbt_pinned_graph.rs +++ b/backend/windmill-api-assets/tests/dbt_pinned_graph.rs @@ -38,6 +38,9 @@ fn outsider() -> ApiAuthed { credential_expiry: None, mcp_client: None, capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), + allowed_ips: None, + admin_withheld: false, + super_admin_withheld: false, } } diff --git a/backend/windmill-api-auth/Cargo.toml b/backend/windmill-api-auth/Cargo.toml index c2cd3a1674..474b8710ea 100644 --- a/backend/windmill-api-auth/Cargo.toml +++ b/backend/windmill-api-auth/Cargo.toml @@ -29,6 +29,7 @@ serde_json.workspace = true uuid.workspace = true itertools.workspace = true tower-cookies.workspace = true +url.workspace = true tracing.workspace = true chrono.workspace = true quick_cache.workspace = true diff --git a/backend/windmill-api-auth/src/auth.rs b/backend/windmill-api-auth/src/auth.rs index 889f1f09a0..9362c3b9f1 100644 --- a/backend/windmill-api-auth/src/auth.rs +++ b/backend/windmill-api-auth/src/auth.rs @@ -15,6 +15,7 @@ use tracing::Span; use crate::{ApiAuthed, OptJobAuthed}; use std::{ + net::IpAddr, str::FromStr, sync::{ atomic::{AtomicI64, AtomicU64, Ordering}, @@ -41,8 +42,61 @@ lazy_static::lazy_static! { pub static ref AUTH_CACHE: Cache<(String, String), ExpiringAuthCache> = Cache::new(300); // Cache for token -> email lookups (for non-workspace-member authenticated users) static ref TOKEN_EMAIL_CACHE: Cache, std::time::Instant)> = Cache::new(500); + // Joined hashes of a request's duplicate `token` cookies -> index of the live one. + static ref PICKED_SESSION_CACHE: Cache, std::time::Instant)> = Cache::new(500); } +/// Throttles the log line for refused IP-restricted tokens: a leaked token hammered from outside +/// its networks would otherwise log once per request. +static REFUSAL_LOG: std::sync::LazyLock = std::sync::LazyLock::new(RefusalLog::default); + +const REFUSAL_LOG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(60); +/// Bounds the memory an attacker cycling through many tokens can pin; a reset only lets each +/// token log once more early. +const REFUSAL_LOG_MAX_TOKENS: usize = 10_000; + +#[derive(Default)] +struct RefusalLog(std::sync::Mutex>); + +impl RefusalLog { + /// Records one refusal of `token_prefix`. Returns the number of its refusals to report when a + /// line is due (the first one, then at most one per interval), `None` while suppressed. + fn note(&self, token_prefix: &str, now: std::time::Instant) -> Option { + let mut map = self.0.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((last, count)) = map.get_mut(token_prefix) { + *count += 1; + if now.duration_since(*last) < REFUSAL_LOG_INTERVAL { + return None; + } + let refused = *count; + *last = now; + *count = 0; + return Some(refused); + } + if map.len() >= REFUSAL_LOG_MAX_TOKENS { + map.clear(); + } + map.insert(token_prefix.to_string(), (now, 0)); + Some(1) + } +} + +fn log_ip_refusal(token_prefix: &str, client_ip: Option) { + if let Some(refused) = REFUSAL_LOG.note(token_prefix, std::time::Instant::now()) { + tracing::warn!( + token_prefix, + client_ip = client_ip.map(|ip| ip.to_string()).unwrap_or_default(), + refused_since_last_log = refused, + "token refused: request is outside the token's allowed IPs" + ); + } +} + +/// Marks a request whose IP refusal was already logged: a failed resolution is not memoized, +/// so a second auth extractor on the same request resolves the token again. +#[derive(Clone)] +struct IpRefusalLogged; + /// A token keeps its identity when a superadmin moves the account to another address, so entries /// here must expire on their own; nothing invalidates them by token hash. const TOKEN_EMAIL_CACHE_TTL_SECS: u64 = 60; @@ -156,16 +210,54 @@ impl AuthCache { AUTH_CACHE.remove(&(w_id.to_string(), token)); } - pub async fn get_authed(&self, w_id: Option, token: &str) -> Option { - Some(self.get_opt_job_authed(w_id, token).await?.authed) + /// `client_ip` is the address of the request presenting `token` (`ClientIp`), `None` outside + /// one: a token restricted to `allowed_ips` resolves only when it is inside them. + pub async fn get_authed( + &self, + w_id: Option, + token: &str, + client_ip: Option, + ) -> Option { + Some( + self.get_opt_job_authed(w_id, token, client_ip) + .await? + .authed, + ) } pub async fn get_opt_job_authed( &self, w_id: Option, token: &str, + client_ip: Option, + ) -> Option { + self.get_opt_job_authed_lazy_ip(w_id, token, move || client_ip, log_ip_refusal) + .await + } + + /// `client_ip` is resolved only for a token that has `allowed_ips`, so the hot path pays + /// nothing for unrestricted tokens. `on_refused` gets the token prefix and address of a + /// request refused for being outside them. + async fn get_opt_job_authed_lazy_ip( + &self, + w_id: Option, + token: &str, + client_ip: impl FnOnce() -> Option, + on_refused: impl FnOnce(&str, Option), ) -> Option { let mut opt_job_authed = self.get_opt_job_authed_inner(w_id.clone(), token).await?; + // Checked per request, outside the cache: the cached identity carries the list, and each + // request brings its own address. + if let Some(allowed) = opt_job_authed.authed.allowed_ips.as_deref() { + let client_ip = client_ip(); + if !crate::client_ip_allowed(Some(allowed), client_ip) { + on_refused( + opt_job_authed.authed.token_prefix.as_deref().unwrap_or(""), + client_ip, + ); + return None; + } + } // Single source of truth: mirror the resolved job_id onto the authed so // every consumer (require_super_admin, ...) sees that this identity came // from a job's WM_TOKEN, even on an AUTH_CACHE hit whose cached authed @@ -358,6 +450,9 @@ impl AuthCache { credential_expiry: Some(credential_expiry), mcp_client: None, capabilities: None, + allowed_ips: None, + admin_withheld: false, + super_admin_withheld: false, }; AUTH_CACHE.insert( key, @@ -405,6 +500,9 @@ impl AuthCache { credential_expiry: None, mcp_client: claims.mcp_client, capabilities: None, + allowed_ips: None, + admin_withheld: claims.admin_withheld, + super_admin_withheld: claims.super_admin_withheld, }; // Fail closed: a `job_id` claim that does not parse must reject // the token rather than resolve to `None`, which would clear the @@ -444,18 +542,23 @@ impl AuthCache { token_hash = $1 AND (expiration > NOW() OR expiration IS NULL) AND (workspace_id IS NULL OR workspace_id = $2) - RETURNING owner, email, super_admin, scopes, label, read_only", + RETURNING owner, email, super_admin, scopes, label, read_only, + allowed_ips::text[] AS allowed_ips, admin", t_hash, w_id.as_ref(), ) .map(|x| { ( - x.owner, - x.email, - x.super_admin, - x.scopes, - x.label, - x.read_only, + ( + x.owner, + x.email, + x.super_admin, + x.scopes, + x.label, + x.read_only, + ), + x.allowed_ips, + x.admin, ) }) .fetch_optional(&self.db) @@ -463,7 +566,12 @@ impl AuthCache { .ok() .flatten(); - if let Some(user) = user_o { + if let Some((user, allowed_ips, token_admin)) = user_o { + let admin_withheld = !token_admin; + // A session always stands for the account as it is; any other row carries + // superadmin rights only if it was minted with them. + let super_admin_withheld = !user.2 && !is_session_label(user.4.as_deref()); + let allowed_ips = crate::token_ip_allowlist_oss::load_allowed_ips(allowed_ips); let authed_o = { match user { (Some(owner), Some(email), super_admin, _, label, read_only) @@ -500,7 +608,12 @@ impl AuthCache { ) .await .unwrap_or(true); - Some((r.is_admin, restricted && !r.is_admin)) + // A withheld admin acts as a member that + // is not restricted, not as an operator. + Some(( + r.is_admin && token_admin, + restricted && !r.is_admin, + )) } None => None, } @@ -538,6 +651,9 @@ impl AuthCache { credential_expiry: None, mcp_client: None, capabilities: None, + allowed_ips: None, + admin_withheld: false, + super_admin_withheld: false, }) } else { tracing::warn!( @@ -594,6 +710,9 @@ impl AuthCache { credential_expiry: None, mcp_client: None, capabilities: None, + allowed_ips: None, + admin_withheld: false, + super_admin_withheld: false, }) } else { tracing::warn!( @@ -681,7 +800,7 @@ impl AuthCache { Some(ApiAuthed { email, username, - is_admin: is_admin || super_admin, + is_admin: (is_admin && token_admin) || super_admin, is_operator, groups, folders, @@ -695,6 +814,9 @@ impl AuthCache { credential_expiry: None, mcp_client: None, capabilities: None, + allowed_ips: None, + admin_withheld: false, + super_admin_withheld: false, }) } None if super_admin => { @@ -722,6 +844,9 @@ impl AuthCache { credential_expiry: None, mcp_client: None, capabilities: None, + allowed_ips: None, + admin_withheld: false, + super_admin_withheld: false, }), Err(e) => { tracing::error!( @@ -762,6 +887,9 @@ impl AuthCache { credential_expiry: None, mcp_client: None, capabilities: None, + allowed_ips: None, + admin_withheld: false, + super_admin_withheld: false, }) } None => None, @@ -784,12 +912,21 @@ impl AuthCache { credential_expiry: None, mcp_client: None, capabilities: None, + allowed_ips: None, + admin_withheld: false, + super_admin_withheld: false, }) } } _ => None, } }; + let authed_o = authed_o.map(|authed| ApiAuthed { + allowed_ips, + admin_withheld, + super_admin_withheld, + ..authed + }); if let Some(authed) = authed_o.as_ref() { AUTH_CACHE.insert( key, @@ -826,6 +963,9 @@ impl AuthCache { credential_expiry: None, mcp_client: None, capabilities: None, + allowed_ips: None, + admin_withheld: false, + super_admin_withheld: false, }; Some(OptJobAuthed { authed, job_id: None }) } else { @@ -956,6 +1096,96 @@ async fn admit_and_record_guest_jwt(db: &DB, w_id: &str, email: &str, app_path: true } +/// Browsers send one or two; checking more would let one request try many guessed tokens +/// while `BRUTE_FORCE_COUNTER` counts a single failure. +const MAX_SESSION_COOKIES: usize = 4; + +/// The first `token` cookie values, parsed the way `Cookies` parses them, in the order sent. +fn session_cookie_values(parts: &Parts) -> Vec { + parts + .headers + .get_all(http::header::COOKIE) + .iter() + .filter_map(|h| h.to_str().ok()) + .flat_map(|h| h.split(';')) + .filter_map(|c| tower_cookies::Cookie::parse_encoded(c).ok()) + .filter(|c| c.name() == COOKIE_NAME) + .map(|c| c.value_trimmed().to_owned()) + .take(MAX_SESSION_COOKIES) + .collect() +} + +/// A browser can hold two `token` cookies for one host: this instance's, and one a parent-domain +/// instance set with `Domain=` (app.windmill.dev on `.windmill.dev`), which JS cannot clear since +/// it is HttpOnly. Browsers disagree on their order (Safari sends the host's first, Chrome last), +/// so neither position can be trusted: keep the first one that is a live session here. +async fn pick_live_session_token( + parts: &mut Parts, + state: &S, + candidates: Vec, +) -> Option { + // `Cookies::get` keeps the last duplicate: the pick when nothing can be checked. + let fallback = candidates.last().cloned(); + let Ok(Extension(cache)) = Extension::>::from_request_parts(parts, state).await + else { + return fallback; + }; + let hashes: Vec = candidates.iter().map(|t| hash_token(t)).collect(); + // A browser keeps sending the same pair on every request, so the pick is cached. A token + // revoked within the TTL can still be picked, and then fails authentication as revoked. + let key = hashes.join(","); + if let Some((picked, at)) = PICKED_SESSION_CACHE.get(&key) { + if at.elapsed().as_secs() < TOKEN_EMAIL_CACHE_TTL_SECS { + return picked.map(|i| candidates[i].clone()).or(fallback); + } + } + let live: Vec = match sqlx::query_scalar( + "SELECT h FROM unnest($1::text[]) AS h \ + WHERE EXISTS (SELECT 1 FROM token WHERE token_hash = h \ + AND (expiration > NOW() OR expiration IS NULL))", + ) + .bind(&hashes) + .fetch_all(&cache.db) + .await + { + Ok(live) => live, + Err(e) => { + tracing::error!("checking duplicate session cookies: {e:#}"); + return fallback; + } + }; + let picked = hashes.iter().position(|h| live.contains(h)); + PICKED_SESSION_CACHE.insert(key, (picked, std::time::Instant::now())); + picked.map(|i| candidates[i].clone()).or(fallback) +} + +/// Set on a request whose session cookie [`refuse_foreign_cookie`] set aside, so that the +/// rejection names the reason rather than reading as a plain logged-out 401. +#[derive(Clone)] +struct ForeignCookieRefused(String); + +/// Whether to set aside the session cookie of a state-changing request sent by a page of +/// another origin (see [`crate::request_site`]). The request then authenticates as if it had no +/// cookie: on its `token` query parameter if it has one, else not at all, so routes that take +/// an optional caller (public apps, approval links, HTTP routes, login callbacks) still serve +/// it anonymously. Safe methods are left to the routes that act on a GET, which check for +/// themselves (`CrossSiteGetGuard`). +fn refuse_foreign_cookie(parts: &mut Parts) -> bool { + if parts.method.is_safe() { + return false; + } + if parts.extensions.get::().is_some() { + return true; + } + let Some(foreign) = crate::request_site::foreign_request(&parts.headers, &parts.uri) else { + return false; + }; + foreign.log("ignoring the session cookie"); + let message = foreign.cookie_refusal_message(&parts.headers); + parts.extensions.insert(ForeignCookieRefused(message)); + true +} + pub(crate) async fn extract_token(parts: &mut Parts, state: &S) -> Option { let auth_header = parts .headers @@ -965,14 +1195,22 @@ pub(crate) async fn extract_token(parts: &mut Parts, state: &S) let from_cookie = match auth_header { Some(x) => Some(x.to_owned()), - None => Extension::::from_request_parts(parts, state) - .await - .ok() - .and_then(|cookies| { - cookies - .get(COOKIE_NAME) - .map(|c| c.value_trimmed().to_owned()) - }), + None => { + let candidates = session_cookie_values(parts); + let cookie = if candidates.len() > 1 { + pick_live_session_token(parts, state, candidates).await + } else { + Extension::::from_request_parts(parts, state) + .await + .ok() + .and_then(|cookies| { + cookies + .get(COOKIE_NAME) + .map(|c| c.value_trimmed().to_owned()) + }) + }; + cookie.filter(|_| !refuse_foreign_cookie(parts)) + } }; #[derive(Deserialize)] @@ -1053,6 +1291,8 @@ where let tokened = Self { token: "no_auth".to_string() }; parts.extensions.insert(tokened.clone()); Ok(tokened) + } else if let Some(ForeignCookieRefused(message)) = parts.extensions.get() { + Err((StatusCode::FORBIDDEN, message.clone())) } else { BRUTE_FORCE_COUNTER.increment().await; Err((StatusCode::UNAUTHORIZED, "Unauthorized".to_owned())) @@ -1154,7 +1394,7 @@ pub fn transform_old_scope_to_new_scope(scopes: Option<&mut Vec>) { } } -fn maybe_get_workspace_id_from_path(path_vec: &[&str]) -> Option { +pub fn maybe_get_workspace_id_from_path(path_vec: &[&str]) -> Option { let workspace_id = if path_vec.len() >= 4 && path_vec[0] == "" && path_vec[2] == "w" { Some(path_vec[3].to_owned()) } else if path_vec.len() >= 5 @@ -1202,6 +1442,9 @@ fn no_auth_admin_authed() -> ApiAuthed { credential_expiry: None, mcp_client: None, capabilities: None, + allowed_ips: None, + admin_withheld: false, + super_admin_withheld: false, } } @@ -1253,71 +1496,36 @@ pub async fn resolve_opt_job_authed( .map(|g| g.0.clone()) }); - if let Some(mut opt_job_authed) = - cache.get_opt_job_authed(workspace_id.clone(), &token).await - { + let mut ip_refused = None; + let resolved = cache + .get_opt_job_authed_lazy_ip( + workspace_id.clone(), + &token, + || windmill_common::client_ip::client_ip_of_parts(&parts), + |prefix, ip| ip_refused = Some((prefix.to_string(), ip)), + ) + .await; + if let Some((prefix, ip)) = ip_refused { + if parts.extensions.get::().is_none() { + log_ip_refusal(&prefix, ip); + parts.extensions.insert(IpRefusalLogged); + } + } + if let Some(mut opt_job_authed) = resolved { let path = original_uri.path(); let method = parts.method.as_str(); - if workspace_id.is_none() && opt_job_authed.job_id.is_some() { - if let Err(err) = crate::scopes::check_job_token_for_global_route(path, method) - { - return Err((err, parts)); - } - } - let own_job_runtime_route = match opt_job_authed.job_id { - Some(job_id) if opt_job_authed.authed.scopes.is_some() => { - crate::scopes::is_own_job_runtime_route(path, method, job_id) - || match crate::scopes::flow_run_read_route_job(path, method) { - Some(target) => { - job_in_same_flow_run(&cache.db, job_id, target).await - } - None => false, - } - } - _ => false, - }; - let authed = &mut opt_job_authed.authed; - if authed.scopes.is_some() && !own_job_runtime_route { - transform_old_scope_to_new_scope(authed.scopes.as_mut()); - if let Some(w_id) = workspace_id.as_deref() { - expand_filter_tags_for_dev_workspace( - &cache.db, - w_id, - authed.scopes.as_mut(), - ) - .await; - } - - if let Err(err) = crate::scopes::check_scopes_for_route( - authed.scopes.as_deref(), - path, - method, - ) { - return Err((err, parts)); - } - } - if authed.read_only { - // MCP transport runs over POST (streamable HTTP / SSE handshake), - // so the middleware can't safely reject mutating methods on it — - // the MCP runner itself filters out write tools and rejects - // mutating tool calls for read-only tokens. Narrow to the actual - // transport endpoints: anything else under `/api/mcp/*` (OAuth - // approve, token exchange, client registration) must still go - // through the read-only check, otherwise a read-only token - // could approve an OAuth flow that mints a new non-read-only - // token. - let is_mcp_transport = path == "/api/mcp/gateway" - || path == "/api/mcp" - || (path.starts_with("/api/mcp/w/") - && (path.ends_with("/mcp") - || path.ends_with("/sse") - || path.ends_with("/list_tools"))); - if !is_mcp_transport { - if let Err(err) = crate::scopes::check_read_only_for_route(path, method) { - return Err((err, parts)); - } - } + if let Err(err) = check_route_layer( + &cache.db, + &mut opt_job_authed, + workspace_id.as_deref(), + path, + method, + ) + .await + { + return Err((err, parts)); } + let authed = &opt_job_authed.authed; parts.extensions.insert(authed.clone()); Span::current().record("username", &authed.username.as_str()); @@ -1348,10 +1556,70 @@ pub async fn resolve_opt_job_authed( } } } + if let Some(ForeignCookieRefused(message)) = parts.extensions.get() { + let message = message.clone(); + return Err((Error::PermissionDenied(message), parts)); + } BRUTE_FORCE_COUNTER.increment().await; Err((Error::NotAuthorized("Unauthorized".to_string()), parts)) } +/// The route checks every request passes before its handler runs: job-token confinement, +/// scopes and `read_only`. `workspace_id` is the request's workspace, `None` on a global route. +/// Normalizes `opt_job_authed`'s scopes in place, as handlers then read them. Token +/// introspection calls this to report a verdict, so a check added to the route layer belongs +/// here rather than beside the call in `resolve_opt_job_authed`. +pub async fn check_route_layer( + db: &DB, + opt_job_authed: &mut OptJobAuthed, + workspace_id: Option<&str>, + path: &str, + method: &str, +) -> windmill_common::error::Result<()> { + if workspace_id.is_none() && opt_job_authed.job_id.is_some() { + crate::scopes::check_job_token_for_global_route(path, method)?; + } + let own_job_runtime_route = match opt_job_authed.job_id { + Some(job_id) if opt_job_authed.authed.scopes.is_some() => { + crate::scopes::is_own_job_runtime_route(path, method, job_id) + || match crate::scopes::flow_run_read_route_job(path, method) { + Some(target) => job_in_same_flow_run(db, job_id, target).await, + None => false, + } + } + _ => false, + }; + let authed = &mut opt_job_authed.authed; + if authed.scopes.is_some() && !own_job_runtime_route { + transform_old_scope_to_new_scope(authed.scopes.as_mut()); + if let Some(w_id) = workspace_id { + expand_filter_tags_for_dev_workspace(db, w_id, authed.scopes.as_mut()).await; + } + crate::scopes::check_scopes_for_route(authed.scopes.as_deref(), path, method)?; + } + if authed.read_only { + // MCP transport runs over POST (streamable HTTP / SSE handshake), + // so the middleware can't safely reject mutating methods on it — + // the MCP runner itself filters out write tools and rejects + // mutating tool calls for read-only tokens. Narrow to the actual + // transport endpoints: anything else under `/api/mcp/*` (OAuth + // approve, token exchange, client registration) must still go + // through the read-only check, otherwise a read-only token + // could approve an OAuth flow that mints a new non-read-only + // token. + let is_mcp_transport = path == "/api/mcp/gateway" + || path == "/api/mcp" + || (path.starts_with("/api/mcp/w/") + && (path.ends_with("/mcp") + || path.ends_with("/sse") + || path.ends_with("/list_tools"))); + if !is_mcp_transport { + crate::scopes::check_read_only_for_route(path, method)?; + } + } + Ok(()) +} + /// Returns the override and whether it names the token's *label* rather than the entity that /// fired the request. Callers must not re-derive the second element from the first: the /// `ephemeral-script-end-user-` arm forwards a `created_by` verbatim, and `created_by` is @@ -1475,6 +1743,24 @@ pub async fn list_tokens_internal( mod tests { use super::*; + #[test] + fn refusal_log_reports_once_per_interval_with_the_count() { + let log = RefusalLog::default(); + let t0 = std::time::Instant::now(); + assert_eq!(log.note("tok_a", t0), Some(1)); + for _ in 0..4 { + assert_eq!( + log.note("tok_a", t0 + std::time::Duration::from_secs(1)), + None + ); + } + // A token of its own is not held back by another's suppression. + assert_eq!(log.note("tok_b", t0), Some(1)); + // The four suppressed refusals plus this one. + assert_eq!(log.note("tok_a", t0 + REFUSAL_LOG_INTERVAL), Some(5)); + assert_eq!(log.note("tok_a", t0 + REFUSAL_LOG_INTERVAL), None); + } + #[test] fn filter_tags_reach_their_dev_workspace_form() { let mut scopes = vec![ diff --git a/backend/windmill-api-auth/src/lib.rs b/backend/windmill-api-auth/src/lib.rs index 640c05623b..c6efabac71 100644 --- a/backend/windmill-api-auth/src/lib.rs +++ b/backend/windmill-api-auth/src/lib.rs @@ -11,7 +11,12 @@ pub mod composed; #[cfg(feature = "private")] pub mod ee; pub mod ee_oss; +pub mod request_site; pub mod scopes; +#[cfg(all(feature = "private", feature = "enterprise"))] +mod token_ip_allowlist_ee; +pub mod token_ip_allowlist_oss; +pub use token_ip_allowlist_oss::{client_ip_allowed, token_ip_allowlist}; use axum::extract::{FromRequestParts, OptionalFromRequestParts, Path, Request, State}; use axum::middleware::Next; @@ -37,6 +42,7 @@ use windmill_common::{ }; use scopes::ScopeDefinition; +use windmill_common::client_ip::IpNet; use windmill_common::scopes::scope_contains; // Re-export key auth types and functions @@ -97,6 +103,18 @@ pub struct ApiAuthed { /// The role's capabilities in the request's workspace (`AuthCache::get_opt_job_authed`); `None` /// outside a request. pub capabilities: Option, + /// The networks the token row this identity came from may be used from (`token.allowed_ips`). + /// Enforced by `AuthCache::get_opt_job_authed` against each request's client IP; a token + /// minted from this identity through `tokens/create` is held within them. + pub allowed_ips: Option>, + /// The token row this identity came from does not carry its owner's workspace admin rights + /// (`token.admin`): `is_admin` is already capped, and a credential minted from this identity + /// must not regain them. + pub admin_withheld: bool, + /// The token row this identity came from does not carry its owner's superadmin rights + /// (`token.super_admin`, sessions excepted). Superadmin gates key off the account's email, + /// so they must read this: [`require_super_admin`], [`is_super_admin_authed`]. + pub super_admin_withheld: bool, } impl ApiAuthed { @@ -191,6 +209,9 @@ impl From for ApiAuthed { credential_expiry: None, mcp_client: value.mcp_client, capabilities: value.capabilities, + allowed_ips: None, + admin_withheld: false, + super_admin_withheld: false, } } } @@ -315,6 +336,13 @@ pub async fn require_super_admin(db: &DB, authed: &ApiAuthed) -> error::Result<( .to_owned(), )); } + if authed.super_admin_withheld { + return Err(Error::NotAuthorized( + "This endpoint requires superadmin rights, which this token does not carry. Create \ + a token with 'Superadmin rights' turned on to call it." + .to_owned(), + )); + } require_super_admin_email(db, &authed.email).await } @@ -323,7 +351,7 @@ pub async fn require_super_admin(db: &DB, authed: &ApiAuthed) -> error::Result<( /// A job's `WM_TOKEN` is never a superadmin regardless of whose email it carries /// (GHSA-hfh4-cx4h-3fcr), so callers naturally fall through to the restricted path. pub async fn is_super_admin_authed(db: &DB, authed: &ApiAuthed) -> error::Result { - if authed.job_id.is_some() { + if authed.job_id.is_some() || authed.super_admin_withheld { return Ok(false); } is_super_admin_email(db, &authed.email).await @@ -438,7 +466,8 @@ where { if let Some(scopes) = authed.scopes.as_ref() { let mut is_scoped_token = false; - let required_scope = ScopeDefinition::from_scope_string(&required())?; + let mut holds_path_scoped = false; + let required_scope = ScopeDefinition::from_required_scope_string(&required())?; for scope in scopes { if !scope.starts_with("if_jobs:filter_tags:") { if !is_scoped_token { @@ -446,22 +475,57 @@ where } match ScopeDefinition::from_scope_string(scope) { - Ok(scope) if scope.includes(&required_scope) => return Ok(()), + Ok(scope) if scope.grants(&required_scope) => return Ok(()), + Ok(scope) if required_scope.resource.is_none() && scope.resource.is_some() => { + let unpathed = ScopeDefinition { resource: None, ..scope }; + holds_path_scoped |= unpathed.grants(&required_scope); + } _ => {} } } } if is_scoped_token { + let required = required_scope.as_string(); + let hint = if holds_path_scoped { + path_scoped_hint(&required) + } else { + String::new() + }; return Err(Error::PermissionDenied(format!( - "Required scope: {}", - required_scope.as_string() + "Required scope: {required}{hint}" ))); } } Ok(()) } +/// Appended when the token holds a path-scoped form of a scope the request needs whole. +fn path_scoped_hint(required: &str) -> String { + format!( + ". This request is not limited to one path, so a path-scoped {required}: does not \ + grant it; add {required}." + ) +} + +/// A trigger or schedule runs what it names as its owner, in a background job that carries no +/// token scopes, so the `jobs:run` scope a direct run would need is checked at save time against +/// the caller's token. +pub fn check_run_scopes<'a>( + authed: &ApiAuthed, + runnables: impl IntoIterator, +) -> error::Result<()> { + for runnable in runnables { + let kind = if runnable.is_flow() { + "flows" + } else { + "scripts" + }; + check_scopes(authed, || format!("jobs:run:{kind}:{}", runnable.path()))?; + } + Ok(()) +} + /// Returns the caller's "real" scope restrictions: every scope other than /// `if_jobs:filter_tags:` tag filters. `None` means the token is unscoped and /// has the full privileges of its user; `Some` means it is restricted to the @@ -570,7 +634,16 @@ pub fn ensure_scopes_within_caller( authed: &ApiAuthed, requested_scopes: Option<&[String]>, ) -> error::Result<()> { - if let Some(caller_restrictions) = scope_restrictions(authed.scopes.as_deref()) { + ensure_scopes_within(authed.scopes.as_deref(), requested_scopes) +} + +/// Whether a credential holding `holder_scopes` covers `requested_scopes`, by the rules of +/// [`ensure_scopes_within_caller`]. +pub fn ensure_scopes_within( + holder_scopes: Option<&[String]>, + requested_scopes: Option<&[String]>, +) -> error::Result<()> { + if let Some(caller_restrictions) = scope_restrictions(holder_scopes) { let Some(requested_restrictions) = scope_restrictions(requested_scopes) else { return Err(Error::PermissionDenied( "A scope-restricted token cannot create or update a token with broader (unscoped) \ @@ -606,6 +679,27 @@ pub fn ensure_scopes_within_caller( .map(|s| s.as_str()) .collect(); + // Some scopes narrow an MCP grant rather than add to it (`mcp:workspaces:`, + // `mcp:read_only`, `mcp:scripts:` beside `mcp:endpoints:`, a path cap the MCP proxy + // keeps), so a requested MCP grant must keep every scope the caller holds. + if requested_restrictions + .iter() + .any(|s| s.starts_with("mcp:") && s.as_str() != "mcp:session") + { + let requested: std::collections::HashSet<&str> = + requested_restrictions.iter().map(|s| s.as_str()).collect(); + if let Some(missing) = caller_restrictions + .iter() + .find(|s| s.as_str() != "mcp:session" && !requested.contains(s.as_str())) + { + return Err(Error::PermissionDenied(format!( + "A scope-restricted token can only grant MCP scopes together with every scope \ + it holds, including '{missing}'. Request the MCP scopes together with \ + '{missing}', or create the token from your session." + ))); + } + } + for requested in requested_restrictions { if requested.starts_with("mcp:") { // `mcp:session` (windmill_mcp's SESSION_SCOPE) grants nothing: it only picks @@ -637,7 +731,7 @@ pub fn ensure_scopes_within_caller( // not be able to mint or rescope a credential that drops or widens the fence // — even if the caller has no other scope restrictions (filter_tags-only // tokens otherwise look "unscoped" to `scope_restrictions`). - if let Some(caller_tags) = first_filter_tags(authed.scopes.as_deref()) { + if let Some(caller_tags) = first_filter_tags(holder_scopes) { let Some(requested_tags) = first_filter_tags(requested_scopes) else { return Err(Error::PermissionDenied( "A token restricted by if_jobs:filter_tags cannot mint or rescope a token that \ @@ -659,6 +753,54 @@ pub fn ensure_scopes_within_caller( Ok(()) } +/// What a stored token grants, as a token edit leaves it. +pub struct TokenGrant<'a> { + pub scopes: Option<&'a [String]>, + pub super_admin: bool, + pub admin: bool, + pub allowed_ips: Option<&'a [IpNet]>, +} + +/// Refuse a token edit that widens the token beyond what `authed` could mint through +/// `tokens/create` right now. Widening a token in place is then never stronger than minting a +/// new one: the scopes, the admin and superadmin rights and the IP allowlist are each held to +/// the caller's, as minting holds them. +pub fn ensure_grant_within_caller(authed: &ApiAuthed, grant: &TokenGrant) -> error::Result<()> { + ensure_scopes_within_caller(authed, grant.scopes)?; + let caller_scoped = authed + .scopes + .as_deref() + .is_some_and(|s| s.iter().any(|x| !x.starts_with("if_jobs:filter_tags:"))); + if grant.super_admin && (caller_scoped || authed.super_admin_withheld) { + return Err(Error::NotAuthorized( + "Only an unscoped token carrying superadmin rights can widen a superadmin token" + .to_string(), + )); + } + if grant.admin && authed.admin_withheld { + return Err(Error::NotAuthorized( + "A token withholding workspace admin rights cannot widen a token carrying them" + .to_string(), + )); + } + if let Some(caller) = authed.allowed_ips.as_deref() { + if !ip_nets_within(caller, grant.allowed_ips) { + return Err(Error::PermissionDenied( + "A token restricted to IP addresses cannot widen a token beyond the networks it \ + may be used from itself" + .to_string(), + )); + } + } + Ok(()) +} + +/// Whether every network of `inner` lies within `outer`. `None` (usable from anywhere) lies +/// within no list. +pub fn ip_nets_within(outer: &[IpNet], inner: Option<&[IpNet]>) -> bool { + inner.is_some_and(|nets| nets.iter().all(|n| outer.iter().any(|o| o.contains(n)))) +} + /// Tags from the first `if_jobs:filter_tags:` scope, matching the /// semantics of [`get_scope_tags`] (which is what the job runtime consults). /// Returns `None` if no such scope is present. @@ -705,11 +847,11 @@ pub fn build_scope_path_predicate( return true; } let required = - match ScopeDefinition::from_scope_string(&format!("{}:{}:{}", domain, action, path)) { + match ScopeDefinition::from_required_scope_string(&format!("{domain}:{action}:{path}")) { Ok(r) => r, Err(_) => return false, }; - parsed.iter().any(|s| s.includes(&required)) + parsed.iter().any(|s| s.grants(&required)) } } @@ -813,7 +955,20 @@ pub async fn require_devops_role(db: &DB, authed: &ApiAuthed) -> error::Result<( .to_owned(), )); } - if is_devops_email(db, &authed.email).await? { + // `is_devops_email` is also true for a superadmin, which a token withholding those rights + // must not pass as: only the account's own devops role counts then. + let is_devops = if authed.super_admin_withheld { + sqlx::query_scalar!( + "SELECT devops FROM password WHERE email = $1", + &authed.email + ) + .fetch_optional(db) + .await? + .unwrap_or(false) + } else { + is_devops_email(db, &authed.email).await? + }; + if is_devops { Ok(()) } else { Err(Error::NotAuthorized( @@ -1179,6 +1334,9 @@ pub async fn fetch_api_authed_from_permissioned_as( credential_expiry: None, mcp_client: None, capabilities: None, + allowed_ips: None, + admin_withheld: false, + super_admin_withheld: false, }; API_AUTHED_CACHE.insert( @@ -1210,9 +1368,19 @@ pub struct NewToken { pub workspace_id: Option, #[serde(default)] pub read_only: Option, - /// An MCP token carries its owner's superadmin rights (every workspace) only when asked. + /// Whether the token carries its owner's superadmin rights (admin in every workspace, the + /// superadmin routes). `None` inherits them, except for an MCP token; the `tokens/create` + /// handler turns `None` into `false`. Never grants rights the owner or caller lacks. #[serde(default)] pub super_admin: Option, + /// Whether the token carries its owner's workspace admin rights, under the same rules as + /// `super_admin` (`None` inherits, the handler withholds unless asked). + #[serde(default)] + pub admin: Option, + /// IPs or CIDRs the token may be used from; `None` is anywhere. [`create_token_internal`] + /// validates it and holds it within the caller's own. + #[serde(default)] + pub allowed_ips: Option>, } impl NewToken { @@ -1232,6 +1400,8 @@ impl NewToken { workspace_id, read_only, super_admin: None, + admin: None, + allowed_ips: None, } } } @@ -1280,7 +1450,20 @@ pub async fn create_token_internal( .scopes .as_deref() .is_some_and(|s| s.iter().any(|scope| scope.starts_with("mcp:"))); - let is_super_admin = is_super_admin && (!is_mcp || token_config.super_admin == Some(true)); + // Held within the caller's own credential, so a token withholding them cannot mint one back. + let is_super_admin = is_super_admin + && !authed.super_admin_withheld + && match token_config.super_admin { + Some(requested) => requested, + None => !is_mcp, + }; + let carries_admin = token_config.admin.unwrap_or(true) && !authed.admin_withheld; + // Here rather than in each handler: every token minted from a caller's identity (app SDK + // and embed tokens, native trigger webhooks included) must inherit its IP restriction. + let allowed_ips = token_ip_allowlist( + authed.allowed_ips.as_deref(), + token_config.allowed_ips.as_deref(), + )?; if *CLOUD_HOSTED { let nb_tokens = sqlx::query_scalar!("SELECT COUNT(*) FROM token WHERE email = $1", &authed.email) @@ -1295,8 +1478,8 @@ pub async fn create_token_internal( } let rows = sqlx::query!( "INSERT INTO token - (token_hash, token_prefix, token, email, label, expiration, super_admin, scopes, workspace_id, read_only) - SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10 + (token_hash, token_prefix, token, email, label, expiration, super_admin, scopes, workspace_id, read_only, allowed_ips, admin) + SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::text[]::cidr[], $12 WHERE $9::varchar IS NULL OR NOT EXISTS( SELECT 1 FROM workspace WHERE id = $9 AND deleted = true )", @@ -1310,6 +1493,8 @@ pub async fn create_token_internal( token_config.scopes.as_ref().map(|x| x.as_slice()), token_config.workspace_id, token_config.read_only.unwrap_or(false), + allowed_ips.as_deref(), + carries_admin, ) .execute(&mut *tx) .await?; @@ -1327,6 +1512,17 @@ pub async fn create_token_internal( ) .await; + let grant = TokenAuditGrant { + label: token_config.label.as_deref(), + expiration: token_config.expiration, + scopes: token_config.scopes.as_deref(), + workspace_id: token_config.workspace_id.as_deref(), + read_only: token_config.read_only.unwrap_or(false), + allowed_ips: allowed_ips.as_deref(), + admin: carries_admin, + super_admin: is_super_admin, + } + .params(); audit_log( &mut *tx, authed, @@ -1334,7 +1530,7 @@ pub async fn create_token_internal( ActionKind::Create, &"global", Some(t_prefix), - None, + Some(audit_params(&grant)), ) .instrument(tracing::info_span!("token", email = &authed.email)) .await?; @@ -1372,6 +1568,59 @@ pub async fn register_token_expiry_notification( } } +/// What a minted token row holds, recorded on its creation's audit entry. Token edits record +/// their fields' values before and after, so a token's history can be replayed from this. +pub struct TokenAuditGrant<'a> { + pub label: Option<&'a str>, + pub expiration: Option>, + pub scopes: Option<&'a [String]>, + pub workspace_id: Option<&'a str>, + pub read_only: bool, + pub allowed_ips: Option<&'a [String]>, + pub admin: bool, + pub super_admin: bool, +} + +impl TokenAuditGrant<'_> { + /// Each value JSON-encoded, so a `null` (none, never, anywhere) stays distinct from `""`. + pub fn params(&self) -> Vec<(&'static str, String)> { + let j = |v: serde_json::Value| v.to_string(); + vec![ + ("label", j(serde_json::json!(self.label))), + ("expiration", j(serde_json::json!(self.expiration))), + ("scopes", j(serde_json::json!(self.scopes))), + ("workspace_id", j(serde_json::json!(self.workspace_id))), + ("read_only", j(serde_json::json!(self.read_only))), + ("allowed_ips", j(serde_json::json!(self.allowed_ips))), + ("admin", j(serde_json::json!(self.admin))), + ("super_admin", j(serde_json::json!(self.super_admin))), + ] + } +} + +/// Audit parameters from owned values, as `audit_log` takes them. +pub fn audit_params<'a>(params: &'a [(&'a str, String)]) -> HashMap<&'a str, &'a str> { + params.iter().map(|(k, v)| (*k, v.as_str())).collect() +} + +/// Replace a token's pending expiry notification after its expiration changed, so a token +/// extended after its warning went out is warned again before the new date. +pub async fn reset_token_expiry_notification( + tx: &mut sqlx::PgConnection, + token_hash: &str, + label: Option<&str>, + expiration: Option>, +) -> Result<()> { + sqlx::query!( + "DELETE FROM token_expiry_notification WHERE token_hash = $1", + token_hash + ) + .execute(&mut *tx) + .await?; + register_token_expiry_notification(tx, token_hash, label, expiration).await; + Ok(()) +} + // ------------ Permission helpers ------------ pub fn get_perm_in_extra_perms_for_authed( @@ -1536,6 +1785,24 @@ pub fn require_path_read_access_for_preview( mod tests { use super::*; + #[test] + fn ip_nets_within_holds_lists_to_the_outer_networks() { + let nets = |v: &[&str]| v.iter().map(|x| x.parse().unwrap()).collect::>(); + let outer = nets(&["10.0.0.0/8", "192.168.1.0/24"]); + assert!(ip_nets_within( + &outer, + Some(&nets(&["10.1.2.3/32", "192.168.1.0/25"])) + )); + assert!(!ip_nets_within(&outer, Some(&nets(&["10.0.0.0/7"])))); + assert!(!ip_nets_within( + &outer, + Some(&nets(&["10.1.0.0/16", "172.16.0.0/12"])) + )); + // Usable from anywhere lies within no list. + assert!(!ip_nets_within(&outer, None)); + assert!(!ip_nets_within(&[], Some(&nets(&["10.0.0.1/32"])))); + } + fn authed_with_scopes(scopes: Option>) -> ApiAuthed { ApiAuthed { scopes: scopes.map(|v| v.into_iter().map(String::from).collect()), @@ -1717,6 +1984,46 @@ mod tests { assert!(require_owner_of_path(&alice, "u/alice/script").is_ok()); } + #[test] + fn check_scopes_reads_the_required_path_literally() { + let authed = authed_with_scopes(Some(vec![ + "jobs:run:scripts:u/alice/ping", + "resources:read:f/team/*", + ])); + assert!(check_scopes(&authed, || "jobs:run:scripts:u/alice/ping".into()).is_ok()); + assert!(check_scopes(&authed, || "resources:read:f/team/db".into()).is_ok()); + for required in [ + "jobs:run:scripts:hub/1/x,u/alice/ping", + "jobs:run:scripts:hub/1/x,*", + "jobs:run:scripts:*", + "jobs:run:scripts:u/*", + "resources:read:CUSTOM_INSTANCE_DB/x,f/team/db", + "resources:read:*", + "resources:read:f/*", + ] { + assert!( + check_scopes(&authed, || required.to_string()).is_err(), + "{required}" + ); + } + let allowed = build_scope_path_predicate(&authed, "resources", "read"); + assert!(!allowed("x,f/team/db")); + assert!(!allowed("*")); + } + + #[test] + fn check_scopes_names_the_whole_scope_a_path_scoped_token_lacks() { + let authed = authed_with_scopes(Some(vec!["variables:read:u/alice/x"])); + let err = check_scopes(&authed, || "variables:read".into()) + .unwrap_err() + .to_string(); + assert!(err.contains("add variables:read."), "{err}"); + let err = check_scopes(&authed, || "resources:write".into()) + .unwrap_err() + .to_string(); + assert!(!err.contains("path-scoped"), "{err}"); + } + #[test] fn predicate_no_scopes_allows_all() { let authed = authed_with_scopes(None); @@ -2076,6 +2383,30 @@ mod tests { .is_ok()); } + #[test] + fn mcp_grant_keeps_every_caller_scope() { + let fenced = authed_with_scopes(Some(vec!["mcp:all", "mcp:workspaces:a", "users:write"])); + for requested in [ + vec!["mcp:all"], + vec!["mcp:all", "users:write"], + vec!["mcp:all", "mcp:workspaces:a"], + ] { + assert!(ensure_scopes_within_caller(&fenced, opt_scopes(Some(requested)).as_deref()) + .is_err()); + } + assert!(ensure_scopes_within_caller( + &fenced, + opt_scopes(Some(vec!["mcp:all", "mcp:workspaces:a", "users:write", "mcp:session"])) + .as_deref() + ) + .is_ok()); + // A grant without MCP scopes is held to ordinary containment. + assert!( + ensure_scopes_within_caller(&fenced, opt_scopes(Some(vec!["users:write"])).as_deref()) + .is_ok() + ); + } + #[test] fn scoped_caller_cannot_escalate_to_wildcard_or_superset() { // Regression for the access-grant-OR vs subset-containment confusion: diff --git a/backend/windmill-api-auth/src/request_site.rs b/backend/windmill-api-auth/src/request_site.rs new file mode 100644 index 0000000000..9e3018ee1e --- /dev/null +++ b/backend/windmill-api-auth/src/request_site.rs @@ -0,0 +1,364 @@ +/* + * 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. + */ + +//! Whether a request was sent by a page of this instance's own origin. +//! +//! The session cookie is `SameSite=Lax`, which a browser attaches to every request from a +//! *same-site* page: any sibling host under the same registrable domain (every +//! `*.windmill.dev` host for a `.windmill.dev` instance, every `*.corp.com` host for +//! `windmill.corp.com`), forms and top-level GETs alike. The cookie is therefore only treated +//! as the caller's intent on requests from the instance's own origin, a bookmark or a typed +//! URL, or a non-browser client. + +use http::{header, HeaderMap, Uri}; +use url::Url; + +/// Hosts, besides the instance's own, whose pages may send requests that authenticate with +/// the session cookie. `*` accepts every site. +pub const TRUSTED_ORIGINS_ENV: &str = "SESSION_COOKIE_TRUSTED_ORIGINS"; + +lazy_static::lazy_static! { + static ref TRUSTED_ORIGINS: TrustedOrigins = TrustedOrigins::parse( + &std::env::var(TRUSTED_ORIGINS_ENV).unwrap_or_default() + ); +} + +#[derive(Debug, Default)] +pub struct TrustedOrigins { + any: bool, + hosts: Vec, +} + +impl TrustedOrigins { + /// A comma-separated list of hosts or origins (`dash.corp.com`, `https://dash.corp.com`). + pub fn parse(value: &str) -> Self { + let mut trusted = TrustedOrigins::default(); + for entry in value.split(',').map(str::trim).filter(|e| !e.is_empty()) { + if entry == "*" { + trusted.any = true; + } else if let Some(host) = Url::parse(entry) + .ok() + .and_then(|u| u.host_str().map(str::to_owned)) + .or_else(|| host_of(entry)) + { + trusted.hosts.push(host); + } else { + tracing::warn!("{TRUSTED_ORIGINS_ENV}: ignoring {entry:?}, not a host or origin"); + } + } + trusted + } + + fn allows(&self, host: &str) -> bool { + self.hosts.iter().any(|h| h.eq_ignore_ascii_case(host)) + } +} + +/// Why a request is taken to come from a page of another origin. +#[derive(Debug)] +pub enum Foreign { + /// `Sec-Fetch-Site` says so (`same-site`, `cross-site`, or a value this code does not know). + Declared(String), + /// No `Sec-Fetch-Site`; `Origin` names another host, or an opaque origin (`null`). + Origin { origin: String, instance_hosts: Vec }, + /// No `Sec-Fetch-Site` and no `Origin`; `Referer` names another host. + Referer { referer: String, instance_hosts: Vec }, +} + +impl Foreign { + /// Logged when a request is refused. The `Origin`/`Referer` legs compare against the hosts + /// the backend can see, so a proxy that rewrites `Host` without setting + /// `X-Forwarded-Host`, with `BASE_URL` naming another host, refuses requests that were + /// same-origin: say so, so it reads as a misconfiguration. + pub fn log(&self, what: &str) { + match self { + Foreign::Declared(site) => { + tracing::info!(sec_fetch_site = %site, "{what}: the request comes from another site") + } + Foreign::Origin { origin: page, instance_hosts } + | Foreign::Referer { referer: page, instance_hosts } => tracing::warn!( + page = %page, + ?instance_hosts, + "{what}: the page that sent the request is on another host; if it was this \ + instance, set `X-Forwarded-Host` on the proxy or configure `BASE_URL`" + ), + } + } + + /// What the caller is told when the session cookie of this request is set aside. The + /// proxy hint is left out when the browser itself declared the page another site. + pub fn cookie_refusal_message(&self, headers: &HeaderMap) -> String { + let (page, proxy_hint) = match self { + Foreign::Origin { origin: page, .. } | Foreign::Referer { referer: page, .. } => { + (Some(page.clone()), true) + } + Foreign::Declared(_) => ( + headers + .get(header::ORIGIN) + .map(|o| String::from_utf8_lossy(o.as_bytes()).into_owned()) + .or_else(|| header_url_host(headers, header::REFERER)), + false, + ), + }; + let from = page.map(|p| format!(" ({p})")).unwrap_or_default(); + let hint = if proxy_hint { + " If that page is this instance, set BASE_URL to the address you browse or have the \ + proxy send X-Forwarded-Host." + } else { + "" + }; + format!( + "This request came from a page on another host{from}; the session cookie is only \ + accepted from this instance's own pages.{hint} {TRUSTED_ORIGINS_HINT} From scripts, \ + send a token in the Authorization header." + ) + } +} + +/// How to let pages of another site use the session cookie. +pub const TRUSTED_ORIGINS_HINT: &str = + "To allow another site, add it to SESSION_COOKIE_TRUSTED_ORIGINS (comma-separated)."; + +/// [`foreign_signal`] against the configured `BASE_URL` and trusted origins. +pub fn foreign_request(headers: &HeaderMap, uri: &Uri) -> Option { + foreign_signal( + headers, + uri, + windmill_common::BASE_URL.load().as_str(), + &TRUSTED_ORIGINS, + ) +} + +/// `Sec-Fetch-Site` decides when present: only `same-origin` and `none` (a bookmark, a typed +/// URL) are this instance's own. Fetch Metadata rides only on potentially trustworthy URLs, so +/// a plain-http instance (and Safari before 16.4) never gets it; then `Origin`, which a +/// browser sends on every non-GET request, must name an instance host, and failing that +/// `Referer`, the only thing a top-level GET navigation carries. A request with none of them +/// is not from a browser page and is not refused. +/// +/// The `Referer` leg is weak: `strict-origin-when-cross-origin` drops it on an https-to-http +/// downgrade, so an https page pointing at a plain-http instance sends neither header there. +pub fn foreign_signal( + headers: &HeaderMap, + uri: &Uri, + base_url: &str, + trusted: &TrustedOrigins, +) -> Option { + if trusted.any { + return None; + } + let page_host = || { + header_url_host(headers, header::ORIGIN) + .or_else(|| header_url_host(headers, header::REFERER)) + }; + if let Some(site) = headers.get("sec-fetch-site") { + let site = String::from_utf8_lossy(site.as_bytes()).to_ascii_lowercase(); + if site == "same-origin" || site == "none" { + return None; + } + if !trusted.hosts.is_empty() && page_host().is_some_and(|h| trusted.allows(&h)) { + return None; + } + return Some(Foreign::Declared(site)); + } + let is_ours = |host: &str| { + trusted.allows(host) + || instance_hosts(headers, uri, base_url).any(|h| h.eq_ignore_ascii_case(host)) + }; + if let Some(origin) = headers.get(header::ORIGIN) { + if header_url_host(headers, header::ORIGIN).is_some_and(|h| is_ours(&h)) { + return None; + } + return Some(Foreign::Origin { + origin: String::from_utf8_lossy(origin.as_bytes()).into_owned(), + instance_hosts: instance_hosts(headers, uri, base_url).collect(), + }); + } + let referer = header_url_host(headers, header::REFERER)?; + (!is_ours(&referer)).then(|| Foreign::Referer { + referer, + instance_hosts: instance_hosts(headers, uri, base_url).collect(), + }) +} + +/// Every host a same-origin request can name. `Host` alone is not enough: a reverse proxy that +/// forwards without preserving it (nginx `proxy_pass` with no `proxy_set_header Host $host`) +/// hands the backend the upstream's name. A browser page cannot set any of these on a request +/// that carries the cookie (a custom header needs a CORS preflight no route grants with +/// credentials), and `BASE_URL` is instance config. Ports are not compared: the dev frontend +/// and the API differ only by port. +fn instance_hosts<'a>( + headers: &'a HeaderMap, + uri: &'a Uri, + base_url: &'a str, +) -> impl Iterator + 'a { + [ + uri.host() + .map(str::to_owned) + .or_else(|| header_host(headers, header::HOST)), + header_host(headers, "x-forwarded-host"), + Url::parse(base_url) + .ok() + .and_then(|url| url.host_str().map(str::to_owned)), + ] + .into_iter() + .flatten() +} + +fn header_url_host(headers: &HeaderMap, name: header::HeaderName) -> Option { + let value = headers.get(name)?.to_str().ok()?; + Url::parse(value).ok()?.host_str().map(str::to_owned) +} + +fn header_host(headers: &HeaderMap, name: impl header::AsHeaderName) -> Option { + host_of(headers.get(name)?.to_str().ok()?) +} + +/// The host in a `Host`-shaped header value: `host[:port]`, where `host` may be a bracketed +/// IPv6 literal, and where a chain of proxies appends to `X-Forwarded-Host` so only the first +/// entry is the one the browser addressed. +pub fn host_of(value: &str) -> Option { + let host = value.split(',').next()?.trim(); + Url::parse(&format!("http://{host}")) + .ok()? + .host_str() + .map(str::to_owned) +} + +#[cfg(test)] +mod tests { + use super::*; + + const BASE: &str = "https://windmill.example"; + + fn signal_with(headers: &[(&str, &str)], trusted: &TrustedOrigins) -> Option { + let mut map = HeaderMap::new(); + for (name, value) in headers { + map.append( + header::HeaderName::from_bytes(name.as_bytes()).unwrap(), + value.parse().unwrap(), + ); + } + foreign_signal( + &map, + &Uri::from_static("/api/w/ws/jobs/run/p/f"), + BASE, + trusted, + ) + } + + fn signal(headers: &[(&str, &str)]) -> Option { + signal_with(headers, &TrustedOrigins::default()) + } + + #[test] + fn sec_fetch_site_decides_when_present() { + for site in ["same-origin", "none", "Same-Origin"] { + assert!(signal(&[("sec-fetch-site", site)]).is_none(), "{site}"); + } + for site in ["same-site", "cross-site", "unknown"] { + assert!( + matches!( + signal(&[("sec-fetch-site", site)]), + Some(Foreign::Declared(_)) + ), + "{site}" + ); + } + // An `Origin` naming the instance does not outvote the browser's own verdict. + assert!(signal(&[ + ("sec-fetch-site", "same-site"), + ("host", "windmill.example"), + ("origin", "https://windmill.example"), + ]) + .is_some()); + // Nor does a foreign `Referer` outvote `same-origin`. + assert!(signal(&[ + ("sec-fetch-site", "same-origin"), + ("host", "windmill.example"), + ("referer", "https://other.example/page"), + ]) + .is_none()); + } + + #[test] + fn origin_then_referer_stand_in_when_sec_fetch_site_is_absent() { + let host = ("host", "windmill-server.internal:8000"); + assert!(signal(&[host, ("origin", "http://windmill.example")]).is_none()); + assert!(signal(&[ + ("host", "windmill.example:8000"), + ("origin", "http://windmill.example:3000") + ]) + .is_none()); + assert!(signal(&[ + host, + ("x-forwarded-host", "alias.example, proxy.internal"), + ("origin", "http://alias.example") + ]) + .is_none()); + assert!(matches!( + signal(&[host, ("origin", "http://hub.example")]), + Some(Foreign::Origin { .. }) + )); + assert!(matches!( + signal(&[host, ("origin", "null")]), + Some(Foreign::Origin { .. }) + )); + // `Origin` outranks `Referer`. + assert!(signal(&[ + host, + ("origin", "http://hub.example"), + ("referer", "http://windmill.example/") + ]) + .is_some()); + assert!(signal(&[host, ("referer", "http://windmill.example/apps")]).is_none()); + assert!(matches!( + signal(&[host, ("referer", "http://hub.example/x")]), + Some(Foreign::Referer { .. }) + )); + // No browser page named: a script, the CLI, a server-side webhook caller. + assert!(signal(&[host]).is_none()); + } + + #[test] + fn trusted_origins_admit_named_sites() { + let trusted = TrustedOrigins::parse(" https://dash.example , tools.example:8443 ,"); + let from = + |site, origin| signal_with(&[("sec-fetch-site", site), ("origin", origin)], &trusted); + assert!(from("same-site", "https://dash.example").is_none()); + assert!(from("same-site", "https://tools.example").is_none()); + assert!(from("same-site", "https://hub.example").is_some()); + // A top-level navigation has no `Origin`; the `Referer` names the page. + assert!(signal_with( + &[ + ("sec-fetch-site", "same-site"), + ("referer", "https://dash.example/p") + ], + &trusted + ) + .is_none()); + assert!(signal_with(&[("origin", "https://dash.example")], &trusted).is_none()); + let any = TrustedOrigins::parse("*"); + assert!(signal_with(&[("sec-fetch-site", "cross-site")], &any).is_none()); + } + + #[test] + fn host_of_strips_port_brackets_and_proxy_chain() { + assert_eq!( + host_of("windmill.example:8000"), + Some("windmill.example".into()) + ); + assert_eq!(host_of("[::1]:8000"), Some("[::1]".into())); + assert_eq!( + host_of("windmill.example, proxy.internal"), + Some("windmill.example".into()) + ); + assert_eq!(host_of(""), None); + assert_eq!(host_of("not a host"), None); + } +} diff --git a/backend/windmill-api-auth/src/scopes.rs b/backend/windmill-api-auth/src/scopes.rs index 2dffbeca51..b475e98b03 100644 --- a/backend/windmill-api-auth/src/scopes.rs +++ b/backend/windmill-api-auth/src/scopes.rs @@ -165,9 +165,23 @@ pub fn check_route_access( format!("{}:{}", required_domain.as_str(), required_action.as_str()) }; + let path_scoped_job_read = required_domain == ScopeDomain::Jobs + && required_action == ScopeAction::Read + && token_scopes.iter().any(|s| { + ScopeDefinition::from_scope_string(s).is_ok_and(|scope| { + scope.domain == "jobs" + && scope.action == "read" + && job_read_scope_paths(&scope).is_some() + }) + }); + let hint = if path_scoped_job_read { + " This route is not limited to given job paths, so a path-scoped jobs:read: does \ + not grant it; add jobs:read." + } else { + "" + }; Err(Error::PermissionDenied(format!( - "Access denied. Required scope: {}", - scope_display + "Access denied. Required scope: {scope_display}.{hint}" ))) } @@ -251,6 +265,11 @@ fn map_http_method_to_action(method: &str, route_path: &str) -> ScopeAction { return ScopeAction::Run; } + // Lists a resource's tools; a POST only so that a navigation cannot reach it. + if method.eq_ignore_ascii_case("POST") && route_path.contains("/resources/mcp_tools/") { + return ScopeAction::Read; + } + match method.to_uppercase().as_str() { "GET" | "HEAD" | "OPTIONS" => ScopeAction::Read, "POST" | "PUT" | "PATCH" | "DELETE" => ScopeAction::Write, @@ -348,7 +367,7 @@ fn extract_domain_from_route( /// exports) and credential minting (`job_view_token`) are deliberately absent — those are /// `jobs:read`. Keep by-id read routes here in sync as they are added, or a run token /// loses the ability to follow its own run through them. -const RUN_WHITELISTED_GET_PATHS: [&'static str; 33] = [ +const RUN_WHITELISTED_GET_PATHS: [&'static str; 35] = [ "jobs_u/get_flow/", "jobs_u/get_root_job_id/", "jobs_u/get/", @@ -362,6 +381,7 @@ const RUN_WHITELISTED_GET_PATHS: [&'static str; 33] = [ "jobs_u/completed/get/", "jobs_u/completed/get_result/", "jobs_u/completed/get_result_maybe/", + "jobs_u/completed/get_result_shape/", "jobs_u/completed/get_timing/", "jobs_u/dispatch_events/", "jobs_u/getupdate/", @@ -377,6 +397,7 @@ const RUN_WHITELISTED_GET_PATHS: [&'static str; 33] = [ "jobs/job_signature/", "jobs/wac_approval_urls/", "jobs/flow/approval_step_detail/", + "jobs/flow/nested_approvals/", "jobs/completed/get/", "jobs/completed/get_result/", "jobs/completed/get_result_maybe/", @@ -534,7 +555,7 @@ fn app_embed_job_route_allowed(suffix: &str) -> bool { // `get_root_job_id` is intentionally absent: its handler has no access check at // all (returns any job's root id by id) and the app never calls it, so denying // it costs nothing and avoids leaking a foreign job's flow lineage. - const ALLOWED: [&str; 15] = [ + const ALLOWED: [&str; 16] = [ "jobs_u/get/", "jobs_u/getupdate/", "jobs_u/getupdate_sse/", @@ -548,6 +569,7 @@ fn app_embed_job_route_allowed(suffix: &str) -> bool { "jobs_u/completed/get/", "jobs_u/completed/get_result/", "jobs_u/completed/get_result_maybe/", + "jobs_u/completed/get_result_shape/", "jobs_u/completed/get_timing/", "jobs_u/queue/cancel/", ]; @@ -575,7 +597,7 @@ fn resource_metadata_route_allowed(suffix: &str) -> bool { /// a direct `require_job_within_read_scope`. `jobs/result_by_id/` is absent because it /// resolves a node up through the enclosing flows, past the job the check admitted. /// A route added here without that check serves a path-scoped token every job. -const READ_PATH_SCOPED_BY_ID_PATHS: [&'static str; 26] = [ +const READ_PATH_SCOPED_BY_ID_PATHS: [&'static str; 28] = [ "jobs_u/get/", "jobs_u/get_logs/", "jobs_u/get_completed_logs_tail/", @@ -587,6 +609,7 @@ const READ_PATH_SCOPED_BY_ID_PATHS: [&'static str; 26] = [ "jobs_u/completed/get/", "jobs_u/completed/get_result/", "jobs_u/completed/get_result_maybe/", + "jobs_u/completed/get_result_shape/", "jobs_u/completed/get_timing/", "jobs_u/dispatch_events/", "jobs_u/getupdate/", @@ -595,6 +618,7 @@ const READ_PATH_SCOPED_BY_ID_PATHS: [&'static str; 26] = [ "jobs_u/get_flow/", "jobs_u/flow/approval_info/", "jobs/flow/approval_step_detail/", + "jobs/flow/nested_approvals/", "jobs/run_progress/", "jobs/flow/user_states/", "jobs/completed/get/", @@ -1343,13 +1367,17 @@ mod tests { #[test] fn jobs_run_reads_are_limited_to_the_by_id_poll_routes() { let job = "/api/w/test/jobs_u/completed/get_result/019ff012-6b1e-0d6b-fc0d-0c85d34d9cec"; + let shape = + "/api/w/test/jobs_u/completed/get_result_shape/019ff012-6b1e-0d6b-fc0d-0c85d34d9cec"; let list = "/api/w/test/jobs/list"; for scope in ["jobs:run", "jobs:run:scripts:u/admin/script"] { // Following the run it started stays available... - assert!( - check_route_access(&[scope.to_string()], job, "GET").is_ok(), - "{scope} must reach the by-id job poll routes" - ); + for route in [job, shape] { + assert!( + check_route_access(&[scope.to_string()], route, "GET").is_ok(), + "{scope} must reach the by-id job poll route {route}" + ); + } // ...but a run grant is not a licence to enumerate the workspace's jobs. assert!( check_route_access(&[scope.to_string()], list, "GET").is_err(), @@ -1447,6 +1475,7 @@ mod tests { for route in [ format!("jobs_u/get/{id}"), format!("jobs_u/completed/get_result/{id}"), + format!("jobs_u/completed/get_result_shape/{id}"), format!("jobs_u/getupdate_sse/{id}"), format!("jobs_u/flow/approval_info/{id}"), "jobs/list".to_string(), diff --git a/backend/windmill-api-auth/src/token_ip_allowlist_oss.rs b/backend/windmill-api-auth/src/token_ip_allowlist_oss.rs new file mode 100644 index 0000000000..3fa370a4d9 --- /dev/null +++ b/backend/windmill-api-auth/src/token_ip_allowlist_oss.rs @@ -0,0 +1,49 @@ +/* + * Author: Windmill Labs, Inc + * 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. + */ + +//! Token IP allowlists are an Enterprise Edition feature. Without it a stored list is ignored +//! (never enforced, never inherited by a minted token) and asking for one is refused. `private` +//! alone is not that edition: community builds carry it. + +use windmill_common::error::Error; + +pub fn token_ip_allowlists_unavailable() -> Error { + Error::BadRequest("Token IP allowlists are a Windmill Enterprise Edition feature".to_string()) +} + +#[cfg(all(feature = "private", feature = "enterprise"))] +pub use crate::token_ip_allowlist_ee::{client_ip_allowed, load_allowed_ips, token_ip_allowlist}; + +#[cfg(not(all(feature = "private", feature = "enterprise")))] +pub use ce::*; + +#[cfg(not(all(feature = "private", feature = "enterprise")))] +mod ce { + use windmill_common::{client_ip::IpNet, error}; + + pub fn load_allowed_ips(_stored: Option>) -> Option> { + None + } + + pub fn client_ip_allowed( + _allowed: Option<&[IpNet]>, + _client_ip: Option, + ) -> bool { + true + } + + pub fn token_ip_allowlist( + _caller: Option<&[IpNet]>, + requested: Option<&[String]>, + ) -> error::Result>> { + match requested { + Some(_) => Err(super::token_ip_allowlists_unavailable()), + None => Ok(None), + } + } +} diff --git a/backend/windmill-api-flows/src/flows.rs b/backend/windmill-api-flows/src/flows.rs index 6f9af28415..01cdfd155d 100644 --- a/backend/windmill-api-flows/src/flows.rs +++ b/backend/windmill-api-flows/src/flows.rs @@ -1561,7 +1561,7 @@ async fn update_flow( .await.map_err(|e| error::Error::internal_err(format!("Error updating flow due to related schedules update: {e:#}")))?; let schedule = sqlx::query_as::<_, Schedule>( - "UPDATE schedule SET path = $1, script_path = $1 WHERE path = $2 AND workspace_id = $3 AND is_flow IS true RETURNING *") + "UPDATE schedule SET path = $1, script_path = $1 WHERE path = $2 AND script_path = $2 AND workspace_id = $3 AND is_flow IS true RETURNING *") .bind(&nf.path) .bind(&flow_path) .bind(&w_id) @@ -2436,6 +2436,7 @@ mod tests { parallelism: None, squash: None, iteration_label: None, + failure_threshold: None, }), stop_after_if: Some(StopAfterIf { expr: "previous.isEmpty()".to_string(), diff --git a/backend/windmill-api-groups/src/groups.rs b/backend/windmill-api-groups/src/groups.rs index 22667e5660..a4da5fd8ce 100644 --- a/backend/windmill-api-groups/src/groups.rs +++ b/backend/windmill-api-groups/src/groups.rs @@ -448,11 +448,10 @@ pub async fn apply_instance_role( .execute(&mut **tx) .await?; - // Update super_admin flag on non-session tokens. A promotion leaves MCP tokens alone: they - // carry superadmin access only when minted with it (`create_token_internal`). + // A demotion strips superadmin from every other token; a promotion grants it to none, + // since a token carries superadmin rights only when it was minted asking for them. sqlx::query!( - "UPDATE token SET super_admin = $1 WHERE email = $2 AND label != 'session' - AND (NOT $1 OR NOT EXISTS (SELECT 1 FROM unnest(scopes) s WHERE s LIKE 'mcp:%'))", + "UPDATE token SET super_admin = false WHERE email = $2 AND label != 'session' AND NOT $1", new_super_admin, email ) diff --git a/backend/windmill-api-integration-tests/tests/ai_routes.rs b/backend/windmill-api-integration-tests/tests/ai_routes.rs index c7f3900226..fb03464e97 100644 --- a/backend/windmill-api-integration-tests/tests/ai_routes.rs +++ b/backend/windmill-api-integration-tests/tests/ai_routes.rs @@ -409,3 +409,69 @@ async fn test_ai_proxy_x_resource_value(db: Pool) -> anyhow::Result<() Ok(()) } + +/// A `$var:` reference in a resource's custom headers reaches the upstream resolved. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_ai_proxy_resolves_header_var_refs(db: Pool) -> anyhow::Result<()> { + use axum::{http::HeaderMap, http::StatusCode, routing::post, Json, Router}; + + initialize_tracing().await; + std::env::set_var("ALLOW_PRIVATE_AI_BASE_URLS", "true"); + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + let app = Router::new().fallback(post(|headers: HeaderMap| async move { + if headers + .get("x-subscription-key") + .and_then(|v| v.to_str().ok()) + == Some("sub-key") + { + Ok(Json(json!({ + "id": "chatcmpl-test", + "object": "chat.completion", + "choices": [{"message": {"role": "assistant", "content": "hello"}}] + }))) + } else { + Err(StatusCode::UNAUTHORIZED) + } + })); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let base_url = format!("http://127.0.0.1:{}/v1", listener.local_addr()?.port()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + + sqlx::query( + "INSERT INTO variable (workspace_id, path, value, is_secret, description, extra_perms) \ + VALUES ('test-workspace', 'f/ai/sub_key', 'sub-key', false, '', '{}'::jsonb)", + ) + .execute(&db) + .await?; + + let value = json!({ + "api_key": "sk-test", + "base_url": base_url, + "headers": { "X-Subscription-Key": "$var:f/ai/sub_key" } + }) + .to_string(); + let encoded: String = value.bytes().map(|b| format!("%{b:02X}")).collect(); + let resp = authed( + client() + .post(format!( + "http://localhost:{port}/api/w/test-workspace/ai/proxy/chat/completions" + )) + .header("X-Provider", "customai") + .header("X-Resource-Value", encoded) + .json(&json!({ + "model": "gpt-4", + "messages": [{"role": "user", "content": "hi"}] + })), + ) + .send() + .await?; + assert_2xx( + resp.status().as_u16(), + &resp.text().await?, + "a $var: reference in a custom header must be resolved", + ); + + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/audit.rs b/backend/windmill-api-integration-tests/tests/audit.rs index 6050ac2e8e..db439726ce 100644 --- a/backend/windmill-api-integration-tests/tests/audit.rs +++ b/backend/windmill-api-integration-tests/tests/audit.rs @@ -66,7 +66,7 @@ async fn test_job_run_is_searchable_by_token_and_by_caller( let port = server.addr.port(); let resp = authed(client().post(format!("http://localhost:{port}/api/users/tokens/create"))) - .json(&json!({ "label": "audit-probe" })) + .json(&json!({ "label": "audit-probe", "super_admin": true })) .send() .await?; assert_eq!(resp.status(), 201); diff --git a/backend/windmill-api-integration-tests/tests/drafts.rs b/backend/windmill-api-integration-tests/tests/drafts.rs index 35bee45682..6d9426e005 100644 --- a/backend/windmill-api-integration-tests/tests/drafts.rs +++ b/backend/windmill-api-integration-tests/tests/drafts.rs @@ -444,6 +444,8 @@ async fn test_transfer_drafts_to_fork(db: Pool) -> anyhow::Result<()> scopes: None, audit_span: None, mcp_client: None, + admin_withheld: false, + super_admin_withheld: false, }) }; let job_id = uuid::Uuid::new_v4().to_string(); diff --git a/backend/windmill-api-integration-tests/tests/fork_clone_on_behalf_of.rs b/backend/windmill-api-integration-tests/tests/fork_clone_on_behalf_of.rs index 10fc0a8028..3e445a7f16 100644 --- a/backend/windmill-api-integration-tests/tests/fork_clone_on_behalf_of.rs +++ b/backend/windmill-api-integration-tests/tests/fork_clone_on_behalf_of.rs @@ -467,3 +467,47 @@ async fn test_fork_repoints_unresolvable_identities(db: Pool) -> anyho Ok(()) } + +/// Labels are compared on the compare page, so a fork that drops them shows every labelled item +/// as changed. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_fork_copies_labels(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base_url = format!("http://localhost:{}/api", server.addr.port()); + + for q in [ + "INSERT INTO resource (workspace_id, path, value, resource_type, labels, created_by) + VALUES ('test-workspace', 'u/test-user/lr', '{}', 'generic', '{a,b}', 'test-user')", + "INSERT INTO variable (workspace_id, path, value, is_secret, description, labels) + VALUES ('test-workspace', 'u/test-user/lv', 'x', false, '', '{a,b}')", + ] { + sqlx::query(q).execute(&db).await?; + } + + let resp = reqwest::Client::new() + .post(format!( + "{base_url}/w/test-workspace/workspaces/create_fork" + )) + .header("Authorization", "Bearer SECRET_TOKEN") + .json(&json!({ "id": "wm-fork-labels", "name": "Fork" })) + .send() + .await?; + assert!( + resp.status().is_success(), + "creating the fork: {}", + resp.text().await? + ); + + let labels: Vec>> = sqlx::query_scalar( + "SELECT labels FROM resource WHERE workspace_id = 'wm-fork-labels' AND path = 'u/test-user/lr' + UNION ALL + SELECT labels FROM variable WHERE workspace_id = 'wm-fork-labels' AND path = 'u/test-user/lv'", + ) + .fetch_all(&db) + .await?; + let ab = Some(vec!["a".to_string(), "b".to_string()]); + assert_eq!(labels, [ab.clone(), ab]); + + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/mcp_gateway_single_credential.rs b/backend/windmill-api-integration-tests/tests/mcp_gateway_single_credential.rs new file mode 100644 index 0000000000..c752048caf --- /dev/null +++ b/backend/windmill-api-integration-tests/tests/mcp_gateway_single_credential.rs @@ -0,0 +1,80 @@ +//! The gateway checks scopes on and acts as one and the same token. +//! +//! A multi-workspace session checks a call against the MCP scopes of `ApiAuthed`, then runs +//! it as the owner of the token the gateway middleware picked. `ApiAuthed` prefers the +//! `token` cookie over `?token=` and the gateway never reads the cookie, so a request +//! carrying both must still be held to the URL token's scopes. +#![cfg(feature = "mcp")] + +use serde_json::{json, Value}; +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +/// Both workspace-less, which puts the gateway in multi-workspace mode. +async fn insert_mcp_tokens(db: &Pool) -> anyhow::Result<()> { + sqlx::query( + "INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin, scopes) VALUES + (encode(sha256('OWNER_ONE_SCRIPT'::bytea), 'hex'), 'OWNER_ONE_', 'OWNER_ONE_SCRIPT', 'test@windmill.dev', 'agent', true, ARRAY['mcp:scripts:u/test-user/weekly_report']), + (encode(sha256('OTHER_MCP_ALL'::bytea), 'hex'), 'OTHER_MCP_', 'OTHER_MCP_ALL', 'test2@windmill.dev', 'mine', false, ARRAY['mcp:all'])", + ) + .execute(db) + .await?; + Ok(()) +} + +/// The endpoint answers `application/json` or a single-event SSE stream. +async fn gateway_post(port: u16, cookie: Option<&str>, body: Value) -> anyhow::Result { + let mut req = reqwest::Client::new() + .post(format!( + "http://localhost:{port}/api/mcp/gateway?token=OWNER_ONE_SCRIPT" + )) + .header("Accept", "application/json, text/event-stream") + .json(&body); + if let Some(cookie) = cookie { + req = req.header("Cookie", format!("token={cookie}")); + } + let text = req.send().await?.text().await?; + let payload = text + .lines() + .find_map(|l| l.strip_prefix("data: ")) + .unwrap_or(text.trim()); + serde_json::from_str(payload).map_err(|e| anyhow::anyhow!("unparseable MCP body {text:?}: {e}")) +} + +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_mcp_gateway_cookie_does_not_widen_url_token( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + set_jwt_secret().await; + insert_mcp_tokens(&db).await?; + let server = ApiServer::start_mcp(db.clone()).await?; + let port = server.addr.port(); + + let call = json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { + "name": "getVariable", + "arguments": { "workspace_id": "test-workspace", "path": "u/test-user/db_password" }, + }}); + let list = json!({ "jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {} }); + + for cookie in [None, Some("OTHER_MCP_ALL")] { + let resp = gateway_post(port, cookie, call.clone()).await?; + assert!( + resp["error"]["message"] + .as_str() + .is_some_and(|m| m.contains("endpoint 'getVariable' not in token scope")), + "cookie {cookie:?}: a one-script token reached getVariable: {resp}" + ); + + let resp = gateway_post(port, cookie, list.clone()).await?; + let tools = resp["result"]["tools"] + .as_array() + .ok_or_else(|| anyhow::anyhow!("no tool list in {resp}"))?; + assert!( + !tools.iter().any(|t| t["name"] == "getVariable"), + "cookie {cookie:?}: a one-script token was offered getVariable" + ); + } + + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/mcp_superadmin_token.rs b/backend/windmill-api-integration-tests/tests/mcp_superadmin_token.rs index 61a9e3130a..59c5641e26 100644 --- a/backend/windmill-api-integration-tests/tests/mcp_superadmin_token.rs +++ b/backend/windmill-api-integration-tests/tests/mcp_superadmin_token.rs @@ -118,6 +118,20 @@ async fn test_mcp_token_super_admin_is_opt_in(db: Pool) -> anyhow::Res "an MCP token without superadmin access cannot approve one that has it" ); + let without_admin = http + .post(format!("{base}/users/tokens/create")) + .bearer_auth("SECRET_TOKEN") + .json(&json!({ "label": "api" })) + .send() + .await? + .text() + .await?; + assert_eq!( + approve(&without_admin, false).await?.status(), + 401, + "a token withholding its owner's admin rights cannot approve a token that carries them" + ); + http.post(format!("{base}/users/update/test@windmill.dev")) .bearer_auth("SECRET_TOKEN") .json(&json!({ "is_super_admin": true })) diff --git a/backend/windmill-api-integration-tests/tests/native_triggers.rs b/backend/windmill-api-integration-tests/tests/native_triggers.rs index 327c9ab9b9..61a877c66c 100644 --- a/backend/windmill-api-integration-tests/tests/native_triggers.rs +++ b/backend/windmill-api-integration-tests/tests/native_triggers.rs @@ -5,7 +5,7 @@ * 1. Resource path change — cleanup old path, recreate at new path * 2. Config loading — workspace-level, instance-level, token update * 3. Channel expiration renewal — should_renew_channel pure logic - * 4. Delete workspace integration — full cascade, cleanup preserves triggers, parse_stop_channel_params + * 4. Delete workspace integration — unlinks connections, cleanup preserves triggers, parse_stop_channel_params */ use serde_json::json; @@ -23,12 +23,12 @@ use windmill_native_triggers::{ get_workspace_integration, github::GitHub, google::{parse_stop_channel_params, should_renew_channel}, - grant_refused, http_error_status, list_native_triggers, list_usable_connections, + http_error_status, list_native_triggers, list_usable_connections, map_external_error, native_trigger_is_enabled, nextcloud::NextCloud, require_native_integration_use, resolve_usable_connection, set_native_trigger_enabled, store_native_trigger, store_workspace_integration, update_native_trigger, - update_oauth_token_resource, External, ExternalReadFailure, HttpRequestError, + External, ExternalReadFailure, HttpRequestError, NativeTriggerConfig, OAuthConfig, ServiceName, }; @@ -69,6 +69,9 @@ fn test_authed() -> ApiAuthed { credential_expiry: None, mcp_client: None, capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), + allowed_ips: None, + admin_withheld: false, + super_admin_withheld: false, } } @@ -155,16 +158,13 @@ fn now_ms() -> i64 { // 1. Several connections of one service // ============================================================================ -/// Each connection keeps its own tokens: a refresh written back for one, or disconnecting one, -/// must not touch another. Providers that rotate refresh tokens invalidate the old one, so a -/// refresh token copied onto the wrong account breaks that account's next refresh. +/// Each connection keeps its own tokens: disconnecting one must not touch another. #[sqlx::test(migrations = "../migrations", fixtures("base"))] async fn test_connections_are_isolated(db: Pool) -> anyhow::Result<()> { let path_a = "u/test-user/native_nextcloud"; let path_b = "u/other-user/native_nextcloud"; - let mut account_a = 0; for (path, token) in [(path_a, "a"), (path_b, "b")] { - let account = setup_oauth_integration( + setup_oauth_integration( &db, ServiceName::Nextcloud, path, @@ -173,33 +173,8 @@ async fn test_connections_are_isolated(db: Pool) -> anyhow::Result<()> None, ) .await?; - if path == path_a { - account_a = account; - } } - update_oauth_token_resource( - &db, - "test-workspace", - account_a, - "access-a2", - Some("refresh-a2"), - ) - .await; - - let a: OAuthConfig = - decrypt_oauth_data(&db, "test-workspace", ServiceName::Nextcloud, Some(path_a)).await?; - let b: OAuthConfig = - decrypt_oauth_data(&db, "test-workspace", ServiceName::Nextcloud, Some(path_b)).await?; - assert_eq!( - (a.access_token.as_str(), a.refresh_token.as_deref()), - ("access-a2", Some("refresh-a2")) - ); - assert_eq!( - (b.access_token.as_str(), b.refresh_token.as_deref()), - ("access-b", Some("refresh-b")) - ); - let mut tx = db.begin().await?; windmill_native_triggers::workspace_integrations::cleanup_connection( &mut *tx, @@ -302,8 +277,6 @@ async fn test_decrypt_workspace_level(db: Pool) -> anyhow::Result<()> assert_eq!(config.access_token, "ws-access-token"); assert_eq!(config.refresh_token.as_deref(), Some("ws-refresh-token")); - assert_eq!(config.client_id, "test-client-id"); - assert_eq!(config.client_secret, "test-client-secret"); assert_eq!(config.base_url, "https://example.com"); Ok(()) @@ -350,9 +323,8 @@ async fn test_decrypt_instance_level(db: Pool) -> anyhow::Result<()> { ) .await?; - assert_eq!(config.client_id, "instance-client-id"); - assert_eq!(config.client_secret, "instance-client-secret"); assert_eq!(config.access_token, "inst-access-token"); + assert_eq!(config.base_url, "https://accounts.google.com"); Ok(()) } @@ -596,7 +568,7 @@ fn test_should_renew_channel_missing_fields() { // ============================================================================ #[sqlx::test(migrations = "../migrations", fixtures("base"))] -async fn test_delete_integration_full_cascade(db: Pool) -> anyhow::Result<()> { +async fn test_delete_integration_unlinks_connections(db: Pool) -> anyhow::Result<()> { let resource_path = "u/test-user/native_gworkspace"; let account_id = setup_oauth_integration( &db, @@ -650,15 +622,15 @@ async fn test_delete_integration_full_cascade(db: Pool) -> anyhow::Res tx.commit().await?; assert!(deleted); - // Verify everything is gone - let var_count: i64 = sqlx::query_scalar!( - "SELECT count(*) FROM variable WHERE workspace_id = 'test-workspace' AND path = $1", + // Scripts and flows may use the resource, so it and its variable stay, unlinked from the + // account that refreshed through the removed app. + let var_account = sqlx::query_scalar!( + "SELECT account FROM variable WHERE workspace_id = 'test-workspace' AND path = $1", resource_path, ) .fetch_one(&db) - .await? - .unwrap_or(0); - assert_eq!(var_count, 0); + .await?; + assert_eq!(var_account, None); let acc_count: i64 = sqlx::query_scalar!( "SELECT count(*) FROM account WHERE workspace_id = 'test-workspace' AND id = $1", @@ -676,7 +648,7 @@ async fn test_delete_integration_full_cascade(db: Pool) -> anyhow::Res .fetch_one(&db) .await? .unwrap_or(0); - assert_eq!(res_count, 0); + assert_eq!(res_count, 1); assert!( get_workspace_integration(&db, "test-workspace", ServiceName::Google) @@ -993,29 +965,6 @@ fn test_provider_404_is_recognized() { )); } -/// Sending a user to reconnect their integration is only right when the token endpoint refused -/// the grant; a busy or broken endpoint has them fix credentials that are fine. -#[test] -fn test_refresh_failures_blame_only_the_grant_they_refuse() { - let refused = |code: u16| grant_refused(Some(StatusCode::from_u16(code).unwrap()), ""); - for code in [400, 401, 403] { - assert!(refused(code), "{code} refuses the grant"); - } - for code in [404, 408, 429, 500, 503] { - assert!(!refused(code), "{code} says nothing about the grant"); - } - assert!(!grant_refused(None, "")); - - // GitHub answers `bad_refresh_token` with HTTP 200, so the body is the only tell. - let ok = Some(StatusCode::OK); - assert!(grant_refused(ok, r#"{"error":"bad_refresh_token"}"#)); - assert!(grant_refused(ok, r#"{"error":"invalid_grant"}"#)); - assert!(!grant_refused( - ok, - r#"{"access_token":"t","token_type":"bearer"}"# - )); -} - /// A service that is busy or broken has not refused anything, and callers react differently to /// the two. GitHub and Google spend a 403 on throttling, where advice about permissions sends /// the reader after a problem they do not have. diff --git a/backend/windmill-api-integration-tests/tests/offboarding.rs b/backend/windmill-api-integration-tests/tests/offboarding.rs index ce5d0578ca..fd9e7ad707 100644 --- a/backend/windmill-api-integration-tests/tests/offboarding.rs +++ b/backend/windmill-api-integration-tests/tests/offboarding.rs @@ -482,12 +482,130 @@ async fn test_offboard_conflicts(db: Pool) -> anyhow::Result<()> { .any(|c| c.as_str().unwrap().contains("conflict_script")), "conflict should mention conflict_script" ); + // The UI resolves each conflict by deleting one side, so both paths must be reported. + let items = body["conflict_items"] + .as_array() + .expect("conflict_items should be array"); + assert_eq!(items.len(), conflicts.len()); + let item = items + .iter() + .find(|c| c["source_path"] == "u/test-user-2/conflict_script") + .expect("conflict_items should include conflict_script"); + assert_eq!(item["kind"], "script"); + assert_eq!(item["target_path"], "u/test-user/conflict_script"); + assert_eq!(item["workspace_id"], "test-workspace"); // No summary when conflicts exist assert!(body["summary"].is_null()); Ok(()) } +/// Usernames may hold `_`, a LIKE wildcard: another user's item matched by it maps to itself, so +/// it must be neither reported as a conflict (which offers to delete it) nor cleaned up as stale. +#[sqlx::test(migrations = "../migrations", fixtures("base", "offboarding_test"))] +async fn test_offboard_conflicts_underscore_username(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + sqlx::query( + "INSERT INTO usr (workspace_id, email, username, is_admin, role) + VALUES ('test-workspace', 'underscore@windmill.dev', 'test_user', false, 'User')", + ) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO variable (workspace_id, path, value, is_secret, description) + VALUES ('test-workspace', 'u/testxuser/var', 'v', false, '')", + ) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO asset (workspace_id, path, kind, usage_path, usage_kind) + VALUES ('test-workspace', 'main', 'datatable', 'u/testxuser/s', 'script')", + ) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO dependency_map (workspace_id, importer_path, importer_kind, imported_path) + VALUES ('test-workspace', 'u/testxuser/s', 'script', 'f/shared/lib')", + ) + .execute(&db) + .await?; + + let resp = authed(client().post(ws_url(port, "offboard/test_user"))) + .json(&json!({ "reassign_to": "u/test-user", "delete_user": false })) + .send() + .await?; + assert_eq!(resp.status(), 200); + let body: serde_json::Value = resp.json().await?; + assert!(body["conflict_items"].is_null(), "{body}"); + let untouched: i64 = sqlx::query_scalar( + "SELECT (SELECT COUNT(*) FROM asset WHERE usage_path = 'u/testxuser/s') + + (SELECT COUNT(*) FROM dependency_map WHERE importer_path = 'u/testxuser/s') + + (SELECT COUNT(*) FROM variable WHERE path = 'u/testxuser/var')", + ) + .fetch_one(&db) + .await?; + assert_eq!(untouched, 3, "another user's rows must survive the reassignment"); + + Ok(()) +} + +/// Resolving a conflict by deleting the target leaves that script's `dependency_map` and `asset` +/// rows behind, on the keys the departing user's rows are renamed onto. +#[sqlx::test(migrations = "../migrations", fixtures("base", "offboarding_test"))] +async fn test_offboard_over_deleted_target(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + sqlx::query( + "INSERT INTO dependency_map (workspace_id, importer_path, importer_kind, imported_path) + VALUES ('test-workspace', 'u/test-user/conflict_script', 'script', 'f/shared/lib'), + ('test-workspace', 'u/test-user-2/conflict_script', 'script', 'f/shared/lib')", + ) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO asset (workspace_id, path, kind, usage_path, usage_kind) + VALUES ('test-workspace', 'main', 'datatable', 'u/test-user/conflict_script', 'script'), + ('test-workspace', 'main', 'datatable', 'u/test-user-2/conflict_script', 'script')", + ) + .execute(&db) + .await?; + let resp = authed(client().post(format!( + "http://localhost:{port}/api/w/test-workspace/scripts/delete/p/u/test-user/conflict_script" + ))) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + + let resp = authed(client().post(ws_url(port, "offboard/test-user-2"))) + .json(&json!({ "reassign_to": "u/test-user", "delete_user": false })) + .send() + .await?; + assert_eq!(resp.status(), 200); + let body: serde_json::Value = resp.json().await?; + assert!(body["summary"].is_object(), "{body}"); + + let importers: Vec = sqlx::query_scalar( + "SELECT importer_path FROM dependency_map + WHERE workspace_id = 'test-workspace' AND imported_path = 'f/shared/lib'", + ) + .fetch_all(&db) + .await?; + assert_eq!(importers, vec!["u/test-user/conflict_script".to_string()]); + let users: Vec = sqlx::query_scalar( + "SELECT usage_path FROM asset WHERE workspace_id = 'test-workspace' AND path = 'main'", + ) + .fetch_all(&db) + .await?; + assert_eq!(users, vec!["u/test-user/conflict_script".to_string()]); + + Ok(()) +} + #[sqlx::test(migrations = "../migrations", fixtures("base", "offboarding_test"))] async fn test_offboard_tokens_deleted(db: Pool) -> anyhow::Result<()> { initialize_tracing().await; diff --git a/backend/windmill-api-integration-tests/tests/resources.rs b/backend/windmill-api-integration-tests/tests/resources.rs index 9f465eed26..f4d6e73c6b 100644 --- a/backend/windmill-api-integration-tests/tests/resources.rs +++ b/backend/windmill-api-integration-tests/tests/resources.rs @@ -946,25 +946,35 @@ async fn test_mcp_tools(db: Pool) -> anyhow::Result<()> { initialize_tracing().await; let server = ApiServer::start(db.clone()).await?; let port = server.addr.port(); + let list_tools = |path: &'static str| async move { + authed(client().post(resource_url(port, "mcp_tools", path))) + .send() + .await + .unwrap() + }; // unauthenticated -> 401 let resp = client() - .get(resource_url(port, "mcp_tools", "u/test-user/mcp_valid")) + .post(resource_url(port, "mcp_tools", "u/test-user/mcp_valid")) .send() .await .unwrap(); assert_eq!(resp.status(), 401); + // A link or redirect to the route must not connect to the resource's server. + let resp = authed_get(port, "mcp_tools", "u/test-user/mcp_valid").await; + assert_eq!(resp.status(), 405); + // not found -> 404 - let resp = authed_get(port, "mcp_tools", "u/test-user/nonexistent").await; + let resp = list_tools("u/test-user/nonexistent").await; assert_eq!(resp.status(), 404); // null value -> 400 - let resp = authed_get(port, "mcp_tools", "u/test-user/mcp_null").await; + let resp = list_tools("u/test-user/mcp_null").await; assert_eq!(resp.status(), 400); // invalid format -> 400 with parse error message - let resp = authed_get(port, "mcp_tools", "u/test-user/mcp_invalid_format").await; + let resp = list_tools("u/test-user/mcp_invalid_format").await; assert_eq!(resp.status(), 400); let body = resp.text().await?; assert!( @@ -973,7 +983,7 @@ async fn test_mcp_tools(db: Pool) -> anyhow::Result<()> { ); // valid MCP resource but unreachable server -> 500 - let resp = authed_get(port, "mcp_tools", "u/test-user/mcp_valid").await; + let resp = list_tools("u/test-user/mcp_valid").await; assert_eq!(resp.status(), 500); let body = resp.text().await?; assert!( diff --git a/backend/windmill-api-integration-tests/tests/settings.rs b/backend/windmill-api-integration-tests/tests/settings.rs index 7fd60ed8e1..f8b4930406 100644 --- a/backend/windmill-api-integration-tests/tests/settings.rs +++ b/backend/windmill-api-integration-tests/tests/settings.rs @@ -204,6 +204,7 @@ async fn test_alert_job_queue_waiting_in_global_settings(db: Pool) -> async fn read_secret_surfaces( base: &str, names: &[&str], + reveal: bool, ) -> anyhow::Result> { let mut paths = vec![ "instance_config".to_string(), @@ -214,9 +215,13 @@ async fn read_secret_surfaces( paths.extend(names.iter().map(|n| format!("global/{n}"))); let mut out = vec![]; for path in paths { - let resp = authed(client().get(format!("{base}/{path}"))) - .send() - .await?; + let resp = authed( + client() + .get(format!("{base}/{path}")) + .query(&[("dangerously_reveal_secrets", reveal)]), + ) + .send() + .await?; let status = resp.status().as_u16(); out.push((path, status, resp.text().await?)); } @@ -252,9 +257,17 @@ async fn test_server_secrets_follow_export_flag(db: Pool) -> anyhow::R let server = ApiServer::start(db.clone()).await?; let base = format!("http://localhost:{}/api/settings", server.addr.port()); - // Default: a full export, so `get-config` and `pull` can migrate an instance. std::env::remove_var("EXPORT_SERVER_SECRETS"); - for (path, status, body) in read_secret_surfaces(&base, &names).await? { + // A read that does not ask for secrets gets them redacted. + for (path, status, body) in read_secret_surfaces(&base, &names, false).await? { + assert_2xx(status, &body, &path); + assert!( + !body.contains("planted-"), + "{path} returned a secret without dangerously_reveal_secrets: {body}" + ); + } + // Asked for, a full export, so `get-config` and `pull` can migrate an instance. + for (path, status, body) in read_secret_surfaces(&base, &names, true).await? { assert_2xx(status, &body, &path); assert!( body.contains("planted-"), @@ -263,7 +276,7 @@ async fn test_server_secrets_follow_export_flag(db: Pool) -> anyhow::R } std::env::set_var("EXPORT_SERVER_SECRETS", "0"); - let withheld = read_secret_surfaces(&base, &names).await; + let withheld = read_secret_surfaces(&base, &names, true).await; std::env::remove_var("EXPORT_SERVER_SECRETS"); for (path, status, body) in withheld? { if path.starts_with("global/") { diff --git a/backend/windmill-api-integration-tests/tests/token_hash.rs b/backend/windmill-api-integration-tests/tests/token_hash.rs index 285f15a9c6..270651001f 100644 --- a/backend/windmill-api-integration-tests/tests/token_hash.rs +++ b/backend/windmill-api-integration-tests/tests/token_hash.rs @@ -342,6 +342,10 @@ async fn test_rotate_webhook_token(db: Pool) -> anyhow::Result<()> { ) .execute(&db) .await?; + sqlx::query("UPDATE token SET allowed_ips = '{10.0.0.0/8}' WHERE token_hash = $1") + .bind(&original_hash) + .execute(&db) + .await?; // Rotate onto a different runnable than the original token was minted for: a rename moves the // trigger, and rotation has to follow it rather than carry the old scopes forward. @@ -361,6 +365,16 @@ async fn test_rotate_webhook_token(db: Pool) -> anyhow::Result<()> { // New token's hash should exist in DB with the per-service label and expiration let new_hash = hash_token(&rotated.new_token); + let allowed_ips: Option> = + sqlx::query_scalar("SELECT allowed_ips::text[] FROM token WHERE token_hash = $1") + .bind(&new_hash) + .fetch_one(&db) + .await?; + assert_eq!( + allowed_ips, + Some(vec!["10.0.0.0/8".to_string()]), + "rotation must keep the token's IP restriction" + ); let new_row = sqlx::query!( "SELECT label, expiration, scopes FROM token WHERE token_hash = $1", new_hash diff --git a/backend/windmill-api-integration-tests/tests/token_rights_opt_in.rs b/backend/windmill-api-integration-tests/tests/token_rights_opt_in.rs new file mode 100644 index 0000000000..cd7910fdda --- /dev/null +++ b/backend/windmill-api-integration-tests/tests/token_rights_opt_in.rs @@ -0,0 +1,95 @@ +//! A token from `tokens/create` carries its owner's workspace admin and superadmin rights only +//! when asked, the superadmin gates honour it although they key off the account's email, and a +//! token withholding them can neither mint one back nor trade itself for a session. + +use serde_json::json; +use sqlx::{Pool, Postgres}; +use windmill_common::{auth::create_jwt_token_withholding, db::Authed}; +use windmill_test_utils::*; + +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_token_rights_are_opt_in(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + set_jwt_secret().await; + let server = ApiServer::start(db.clone()).await?; + let base = format!("http://localhost:{}/api", server.addr.port()); + let http = reqwest::Client::new(); + + let mint = |bearer: &str, body: serde_json::Value| { + http.post(format!("{base}/users/tokens/create")) + .bearer_auth(bearer.to_string()) + .json(&body) + .send() + }; + // SECRET_TOKEN's owner is a superadmin and an admin of test-workspace. + let status = |path: &str, token: &str| { + http.get(format!("{base}{path}")) + .bearer_auth(token.to_string()) + .send() + }; + let admin_route = "/w/test-workspace/workspaces/list_pending_invites"; + let superadmin_route = "/users/list_as_super_admin"; + + let plain = mint("SECRET_TOKEN", json!({})).await?.text().await?; + assert_eq!(status(admin_route, &plain).await?.status(), 403); + assert_eq!(status(superadmin_route, &plain).await?.status(), 401); + + let admin = mint("SECRET_TOKEN", json!({ "admin": true })) + .await? + .text() + .await?; + assert_eq!(status(admin_route, &admin).await?.status(), 200); + assert_eq!(status(superadmin_route, &admin).await?.status(), 401); + + let superadmin = mint("SECRET_TOKEN", json!({ "super_admin": true })) + .await? + .text() + .await?; + assert_eq!(status(superadmin_route, &superadmin).await?.status(), 200); + + let regained = mint(&plain, json!({ "admin": true, "super_admin": true })) + .await? + .text() + .await?; + assert_eq!(status(admin_route, ®ained).await?.status(), 403); + assert_eq!(status(superadmin_route, ®ained).await?.status(), 401); + + // A JWT minted from such a token (the AI session tools mint one per call) keeps the caps. + let caller_jwt = create_jwt_token_withholding( + Authed { + email: "test@windmill.dev".to_string(), + username: "test-user".to_string(), + is_admin: false, + is_operator: false, + groups: vec![], + folders: vec![], + scopes: None, + token_prefix: None, + mcp_client: None, + capabilities: None, + }, + "test-workspace", + 3600, + None, + None, + None, + None, + (true, true), + ) + .await?; + assert_eq!(status(superadmin_route, &caller_jwt).await?.status(), 401); + let from_jwt = mint(&caller_jwt, json!({ "admin": true, "super_admin": true })) + .await? + .text() + .await?; + assert_eq!(status(admin_route, &from_jwt).await?.status(), 403); + assert_eq!(status(superadmin_route, &from_jwt).await?.status(), 401); + + assert_eq!( + status("/users/refresh_token", &plain).await?.status(), + 401, + "a session would carry the rights the token withholds" + ); + + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/token_risk.rs b/backend/windmill-api-integration-tests/tests/token_risk.rs new file mode 100644 index 0000000000..c2c2ae6634 --- /dev/null +++ b/backend/windmill-api-integration-tests/tests/token_risk.rs @@ -0,0 +1,196 @@ +//! The `token_risk` view flags what a token review looks at, and the superadmin review (EE) +//! pages through it with a cursor, so a token used between two pages is not skipped. Without +//! `enterprise` (the CE image builds `private` alone), only its counts are served. + +use sqlx::{Pool, Postgres, Row}; +use windmill_test_utils::*; + +/// A token with no risk: bound to test-workspace, expiring, just used, minted without rights. +async fn insert_token(db: &Pool, prefix: &str, email: &str) { + sqlx::query( + "INSERT INTO token (token_hash, token_prefix, email, label, expiration, workspace_id, \ + super_admin, admin) \ + VALUES (md5($1), $1, $2, $1, now() + interval '30 days', 'test-workspace', false, false)", + ) + .bind(prefix) + .bind(email) + .execute(db) + .await + .unwrap(); +} + +async fn update(db: &Pool, prefix: &str, set: &str) { + sqlx::query(&format!("UPDATE token SET {set} WHERE token_prefix = $1")) + .bind(prefix) + .execute(db) + .await + .unwrap(); +} + +async fn risks(db: &Pool, prefix: &str) -> Vec { + sqlx::query("SELECT risks FROM token_risk WHERE token_prefix = $1") + .bind(prefix) + .fetch_one(db) + .await + .unwrap() + .get("risks") +} + +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_token_risk_rules(db: Pool) -> anyhow::Result<()> { + // test@ is an admin of test-workspace, test2@ only a member. + let admin = "test@windmill.dev"; + let member = "test2@windmill.dev"; + let cases: &[(&str, &str, &str, &[&str])] = &[ + ("clean", admin, "read_only = false", &[]), + ("never", admin, "expiration = NULL", &["never_expires"]), + ("unbound", admin, "workspace_id = NULL", &["all_workspaces"]), + ( + "stale", + admin, + "last_used_at = now() - interval '91 days'", + &["unused"], + ), + ( + "recent", + admin, + "last_used_at = now() - interval '89 days'", + &[], + ), + ( + "sa", + admin, + "super_admin = true, admin = true", + &["superadmin"], + ), + ("adm", admin, "admin = true", &["admin"]), + // Rights the owner does not hold are not flagged, nor rights the token was minted without. + ("member", member, "admin = true", &[]), + // Scopes or read-only mode narrow the rights; a job tag filter alone does not. + ("scoped", admin, "admin = true, scopes = '{jobs:read}'", &[]), + ("ro", admin, "admin = true, read_only = true", &[]), + ( + "tags", + admin, + "admin = true, scopes = '{if_jobs:filter_tags:prod}'", + &["admin"], + ), + ]; + for (prefix, email, set, expected) in cases { + insert_token(&db, prefix, email).await; + update(&db, prefix, set).await; + assert_eq!(&risks(&db, prefix).await, expected, "{prefix}"); + } + + // Tokens the server manages on its own carry no flag, however risky they look: a label + // only the server mints, or a system label `tokens/create` also accepts on a token as + // short-lived as the system's own. The same label on a long-lived token proves nothing. + let managed: &[(&str, &str, bool)] = &[ + ("session", "expiration = NULL", true), + ("ephemeral-script", "expiration = NULL", true), + ("mcp-oauth-x", "expiration = NULL", true), + ("impersonation:a", "expiration = created_at + interval '24 hours'", true), + ("Ephemeral lsp token", "expiration = created_at + interval '72 hours'", true), + ("debugger-token", "expiration = NULL", false), + ("sdk_app:f", "expiration = created_at + interval '30 days'", false), + ]; + for (i, (label, expiration, exempt)) in managed.iter().enumerate() { + let prefix = format!("managed-{i}"); + insert_token(&db, &prefix, admin).await; + update( + &db, + &prefix, + &format!("label = '{label}', {expiration}, workspace_id = NULL, super_admin = true"), + ) + .await; + assert_eq!(risks(&db, &prefix).await.is_empty(), *exempt, "{label}"); + } + Ok(()) +} + +#[cfg(feature = "enterprise")] +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_token_review_cursor_survives_use(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let url = format!( + "http://localhost:{}/api/users/tokens/list_as_super_admin", + server.addr.port() + ); + let http = reqwest::Client::new(); + + // Flagged (no expiration) and staler than the fixture's tokens, in this order. + for (prefix, days) in [("page-a", 12), ("page-b", 11), ("page-c", 10)] { + insert_token(&db, prefix, "test@windmill.dev").await; + update( + &db, + prefix, + &format!("expiration = NULL, last_used_at = now() - interval '{days} days'"), + ) + .await; + } + + let first: serde_json::Value = http + .get(&url) + .bearer_auth("SECRET_TOKEN") + .query(&[("per_page", "1")]) + .send() + .await? + .json() + .await?; + let a = &first[0]; + assert_eq!(a["token_prefix"], "page-a"); + + // page-a is used before the next page is read, which moves it to the end of the order: + // an offset would now skip page-b. + update(&db, "page-a", "last_used_at = now()").await; + + let next: serde_json::Value = http + .get(&url) + .bearer_auth("SECRET_TOKEN") + .query(&[ + ("per_page", "1"), + ("after_last_used_at", a["last_used_at"].as_str().unwrap()), + ("after_token_prefix", "page-a"), + ]) + .send() + .await? + .json() + .await?; + assert_eq!(next[0]["token_prefix"], "page-b"); + Ok(()) +} + +#[cfg(not(feature = "enterprise"))] +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_token_review_list_is_ee(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base = format!("http://localhost:{}/api/users/tokens", server.addr.port()); + let http = reqwest::Client::new(); + insert_token(&db, "victim", "test2@windmill.dev").await; + + let counts = http + .get(format!("{base}/risk_counts_as_super_admin")) + .bearer_auth("SECRET_TOKEN") + .send() + .await?; + assert_eq!(counts.status(), 200); + let list = http + .get(format!("{base}/list_as_super_admin")) + .bearer_auth("SECRET_TOKEN") + .send() + .await?; + assert_eq!(list.status(), 400); + let delete = http + .delete(format!("{base}/delete_as_super_admin/test2@windmill.dev/victim")) + .bearer_auth("SECRET_TOKEN") + .send() + .await?; + assert_eq!(delete.status(), 400); + let left: i64 = sqlx::query_scalar("SELECT count(*) FROM token WHERE token_prefix = 'victim'") + .fetch_one(&db) + .await?; + assert_eq!(left, 1); + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/users.rs b/backend/windmill-api-integration-tests/tests/users.rs index 15f3a2d853..cd92cbb49b 100644 --- a/backend/windmill-api-integration-tests/tests/users.rs +++ b/backend/windmill-api-integration-tests/tests/users.rs @@ -77,7 +77,7 @@ async fn test_user_endpoints(db: Pool) -> anyhow::Result<()> { // --- tokens/create --- let resp = authed(client().post(format!("{global_base}/tokens/create"))) - .json(&json!({"label": "ephemeral-test-token"})) + .json(&json!({"label": "test-token"})) .send() .await .unwrap(); @@ -1639,3 +1639,190 @@ async fn test_generated_username_skips_anonymous(db: Pool) -> anyhow:: assert_eq!(username, "anonymous2"); Ok(()) } + +/// The `admin` column defaults to true, so the list must report the rights the owner holds, +/// not the opt-in alone. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_list_tokens_reports_carried_rights(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let url = format!( + "http://localhost:{}/api/users/tokens/list", + server.addr.port() + ); + + let rights = |token: &'static str| { + let url = url.clone(); + async move { + let tokens = client() + .get(url) + .header("Authorization", format!("Bearer {token}")) + .send() + .await? + .json::() + .await?; + let t = tokens + .as_array() + .and_then(|a| { + a.iter() + .find(|t| t["label"].as_str().unwrap_or("").starts_with("test token")) + }) + .cloned() + .ok_or_else(|| anyhow::anyhow!("fixture token not listed: {tokens}"))?; + anyhow::Ok((t["admin"].as_bool(), t["super_admin"].as_bool())) + } + }; + + // test@: workspace admin and superadmin, token opted in to both. + assert_eq!(rights("SECRET_TOKEN").await?, (Some(true), Some(true))); + // test2@: a plain member, whose token carries the column's default `admin = true`. + assert_eq!(rights("SECRET_TOKEN_2").await?, (Some(false), Some(false))); + + // An unlabeled token of a superadmin owner, minted without superadmin rights: it must + // list as such rather than break the list. + sqlx::query( + "INSERT INTO token (token_hash, token_prefix, email, label, super_admin) + VALUES (encode(sha256('UNLABELED'::bytea), 'hex'), 'UNLABELED0', 'test@windmill.dev', NULL, false)", + ) + .execute(&db) + .await?; + let tokens = client() + .get(&url) + .header("Authorization", "Bearer SECRET_TOKEN") + .send() + .await? + .error_for_status()? + .json::() + .await?; + let unlabeled = tokens + .as_array() + .and_then(|a| a.iter().find(|t| t["token_prefix"] == "UNLABELED0")) + .ok_or_else(|| anyhow::anyhow!("unlabeled token not listed: {tokens}"))?; + assert_eq!(unlabeled["super_admin"], false); + + // Withheld admin is reported as such even for an admin owner. + sqlx::query( + "UPDATE token SET admin = false, super_admin = false WHERE email = 'test@windmill.dev'", + ) + .execute(&db) + .await?; + assert_eq!(rights("SECRET_TOKEN").await?, (Some(false), Some(false))); + Ok(()) +} + +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_token_edits_widen_only_as_far_as_the_caller_could_mint( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base = format!("http://localhost:{}/api/users/tokens", server.addr.port()); + let post = |token: String, path: String, body: serde_json::Value| { + let url = format!("{base}/{path}"); + async move { + let resp = client() + .post(url) + .header("Authorization", format!("Bearer {token}")) + .json(&body) + .send() + .await?; + let status = resp.status().as_u16(); + anyhow::Ok((status, resp.text().await?)) + } + }; + let mint = |body: serde_json::Value| { + let post = post.clone(); + async move { + let (status, token) = post("SECRET_TOKEN".into(), "create".into(), body).await?; + anyhow::ensure!(status == 201, "create: {token}"); + anyhow::Ok(token) + } + }; + let prefix = |t: &str| t[..10].to_string(); + let in_days = |d: u64| { + (sqlx::types::chrono::Utc::now() + std::time::Duration::from_secs(d * 86400)).to_rfc3339() + }; + + let target = prefix(&mint(json!({"label": "target", "expiration": in_days(10)})).await?); + let scoped = mint(json!({"label": "scoped", "scopes": ["users:write"]})).await?; + + // A scoped caller may shorten an unscoped token, never extend it: it could not mint one. + let limits = format!("update_limits/{target}"); + let (s, body) = post( + scoped.clone(), + limits.clone(), + json!({"expiration": in_days(5)}), + ) + .await?; + assert_eq!(s, 200, "{body}"); + let (s, body) = post( + scoped.clone(), + limits.clone(), + json!({"expiration": in_days(20)}), + ) + .await?; + assert_eq!(s, 403, "{body}"); + let (s, body) = post(scoped.clone(), limits.clone(), json!({"expiration": null})).await?; + assert_eq!(s, 403, "{body}"); + let (s, body) = post( + "SECRET_TOKEN".into(), + limits, + json!({"expiration": in_days(20)}), + ) + .await?; + assert_eq!(s, 200, "{body}"); + // Other API servers evict their cached copy of the edited token. + let evicted: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM notify_event + WHERE channel = 'notify_token_invalidation' AND payload = $1)", + ) + .bind(&target) + .fetch_one(&db) + .await?; + assert!(evicted); + + // Widening the scopes of a superadmin token needs a caller that could mint superadmin. + let sa = prefix( + &mint( + json!({"label": "sa", "super_admin": true, "scopes": ["scripts:read", "users:write"]}), + ) + .await?, + ); + let scoped2 = + mint(json!({"label": "s2", "scopes": ["scripts:read", "scripts:write", "users:write"]})) + .await?; + let rescope = format!("update_scopes/{sa}"); + let widen = json!({"scopes": ["scripts:write", "users:write"]}); + let (s, body) = post(scoped2.clone(), rescope.clone(), widen.clone()).await?; + assert_eq!(s, 401, "{body}"); + let (s, body) = post(scoped2, rescope.clone(), json!({"scopes": ["users:write"]})).await?; + assert_eq!(s, 200, "{body}"); + let (s, body) = post("SECRET_TOKEN".into(), rescope, widen).await?; + assert_eq!(s, 200, "{body}"); + + // A system-labelled token only narrows, and keeps its server-managed lifetime. + let embed = prefix(&mint(json!({"label": "embed_app:x", "scopes": ["scripts:read"]})).await?); + let rescope = format!("update_scopes/{embed}"); + let (s, body) = post( + "SECRET_TOKEN".into(), + rescope.clone(), + json!({"scopes": null}), + ) + .await?; + assert_eq!(s, 400, "{body}"); + let (s, body) = post( + "SECRET_TOKEN".into(), + rescope, + json!({"scopes": ["scripts:read:f/x"]}), + ) + .await?; + assert_eq!(s, 200, "{body}"); + let (s, body) = post( + "SECRET_TOKEN".into(), + format!("update_limits/{embed}"), + json!({"expiration": in_days(1)}), + ) + .await?; + assert_eq!(s, 400, "{body}"); + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/workspace_comparison.rs b/backend/windmill-api-integration-tests/tests/workspace_comparison.rs index 830a29e8c2..27e5303fe0 100644 --- a/backend/windmill-api-integration-tests/tests/workspace_comparison.rs +++ b/backend/windmill-api-integration-tests/tests/workspace_comparison.rs @@ -2592,9 +2592,12 @@ async fn test_rename_records_the_vacated_path(db: Pool) -> anyhow::Res } /// Regression: a resource or resource type can be stored with a NULL description while deploy -/// writes "", so the comparison must read the two as equal or the item never settles. +/// writes "", and labels as NULL or `{}`, so the comparison must read each pair as equal or the +/// item never settles. A difference in labels alone is still a change. #[sqlx::test(migrations = "../migrations", fixtures("base"))] -async fn test_compare_null_description_equals_empty(db: Pool) -> anyhow::Result<()> { +async fn test_compare_null_description_and_labels_equal_empty( + db: Pool, +) -> anyhow::Result<()> { initialize_tracing().await; let server = ApiServer::start(db.clone()).await?; @@ -2616,6 +2619,11 @@ async fn test_compare_null_description_equals_empty(db: Pool) -> anyho ('wm-fork-test-workspace', 'u/test-user/null_desc', '{}', 'generic', '', 'test-user'), ('test-workspace', 'u/test-user/other_desc', '{}', 'generic', NULL, 'test-user'), ('wm-fork-test-workspace', 'u/test-user/other_desc', '{}', 'generic', 'x', 'test-user')", + "INSERT INTO resource (workspace_id, path, value, resource_type, labels, created_by) VALUES + ('test-workspace', 'u/test-user/null_labels', '{}', 'generic', NULL, 'test-user'), + ('wm-fork-test-workspace', 'u/test-user/null_labels', '{}', 'generic', '{}', 'test-user'), + ('test-workspace', 'u/test-user/other_labels', '{}', 'generic', NULL, 'test-user'), + ('wm-fork-test-workspace', 'u/test-user/other_labels', '{}', 'generic', '{x}', 'test-user')", "INSERT INTO resource_type (workspace_id, name, schema, description, created_by) VALUES ('test-workspace', 'null_desc_rt', '{}', NULL, 'test-user'), ('wm-fork-test-workspace', 'null_desc_rt', '{}', '', 'test-user'), @@ -2626,7 +2634,9 @@ async fn test_compare_null_description_equals_empty(db: Pool) -> anyho ('test-workspace', 'wm-fork-test-workspace', 'u/test-user/null_desc', 'resource', 1, 1, NULL), ('test-workspace', 'wm-fork-test-workspace', 'u/test-user/other_desc', 'resource', 1, 1, NULL), ('test-workspace', 'wm-fork-test-workspace', 'null_desc_rt', 'resource_type', 1, 1, NULL), - ('test-workspace', 'wm-fork-test-workspace', 'other_desc_rt', 'resource_type', 1, 1, NULL)", + ('test-workspace', 'wm-fork-test-workspace', 'other_desc_rt', 'resource_type', 1, 1, NULL), + ('test-workspace', 'wm-fork-test-workspace', 'u/test-user/null_labels', 'resource', 1, 1, NULL), + ('test-workspace', 'wm-fork-test-workspace', 'u/test-user/other_labels', 'resource', 1, 1, NULL)", ] { sqlx::query(q).execute(&db).await?; } @@ -2649,7 +2659,11 @@ async fn test_compare_null_description_equals_empty(db: Pool) -> anyho paths.sort(); assert_eq!( paths, - ["other_desc_rt", "u/test-user/other_desc"], + [ + "other_desc_rt", + "u/test-user/other_desc", + "u/test-user/other_labels" + ], "{comparison}" ); diff --git a/backend/windmill-api-jobs/src/jobs_export.rs b/backend/windmill-api-jobs/src/jobs_export.rs index 09a6f976ef..e5a7e176b2 100644 --- a/backend/windmill-api-jobs/src/jobs_export.rs +++ b/backend/windmill-api-jobs/src/jobs_export.rs @@ -22,7 +22,7 @@ use windmill_common::{ worker::CLOUD_HOSTED, }; -use windmill_api_auth::ApiAuthed; +use windmill_api_auth::{check_scopes, ApiAuthed}; #[derive(Serialize, Deserialize)] pub struct ExportableCompletedJob { @@ -440,6 +440,8 @@ pub async fn import_queued_jobs( Json(jobs): Json>, ) -> error::Result { require_admin(authed.is_admin, &authed.username)?; + // Imported rows carry their own code and run as soon as a worker picks them up. + check_scopes(&authed, || "jobs:run".to_string())?; // Self-hosted migration/restore tool. It writes queue rows straight to the DB, bypassing the // push path and every admission check that lives there, so it has no place on multi-tenant diff --git a/backend/windmill-api-schedule/src/lib.rs b/backend/windmill-api-schedule/src/lib.rs index aff47aee8c..3755d819f7 100644 --- a/backend/windmill-api-schedule/src/lib.rs +++ b/backend/windmill-api-schedule/src/lib.rs @@ -17,8 +17,8 @@ use sql_builder::{prelude::Bind, SqlBuilder}; use sqlx::{Postgres, Transaction}; use std::str::FromStr; use windmill_api_auth::{ - build_scope_path_predicate, check_scopes, composed::check_new_hub_paths, maybe_refresh_folders, - require_super_admin, ApiAuthed, + build_scope_path_predicate, check_run_scopes, check_scopes, composed::check_new_hub_paths, + maybe_refresh_folders, require_super_admin, ApiAuthed, }; use windmill_audit::audit_oss::audit_log; use windmill_audit::ActionKind; @@ -274,6 +274,10 @@ async fn validate_dynamic_skip<'c>( } } +fn dynamic_skip_runnable(path: Option<&str>) -> Option { + RunnableRef::from_path(path?, false).ok() +} + /// A handler that does not parse is left out: it never runs, as a fire parses it the same way. fn handler_runnables(handlers: [Option<&str>; 3]) -> Vec { handlers @@ -381,6 +385,12 @@ async fn create_schedule( ]); new_runnables.extend(target); check_new_hub_paths(&new_runnables, &[], &authed, &db, &w_id).await?; + check_run_scopes( + &authed, + new_runnables + .iter() + .chain(&dynamic_skip_runnable(ns.dynamic_skip.as_deref())), + )?; let mut tx: Transaction<'_, Postgres> = user_db.begin(&authed).await?; @@ -646,6 +656,21 @@ async fn edit_schedule( &w_id, ) .await?; + // The edit sets the stored target's args, so its run scope is checked as on create. + let target = before.as_ref().and_then(|b| { + RunnableRef::from_path( + b.get("script_path")?.as_str()?, + b.get("is_flow")?.as_bool()?, + ) + .ok() + }); + check_run_scopes( + &authed, + new_handlers + .iter() + .chain(&target) + .chain(&dynamic_skip_runnable(es.dynamic_skip.as_deref())), + )?; let schedule = sqlx::query_as!( Schedule, diff --git a/backend/windmill-api-scripts/src/scripts.rs b/backend/windmill-api-scripts/src/scripts.rs index e063874533..1102db5fe1 100644 --- a/backend/windmill-api-scripts/src/scripts.rs +++ b/backend/windmill-api-scripts/src/scripts.rs @@ -1681,7 +1681,14 @@ async fn create_script_internal<'c>( // it carries a first deploy's lineage, so redeploying content the path has held // before collides with that archived version instead of superseding it. The // folder-derived `on_behalf_of` set further up is likewise covered by the hash. - let hash = ScriptHash(hash_script(&ns)); + // The resolved identity and the deployer are hashed too: script info is cached by + // (workspace id, hash) with no expiry, and a workspace id can be reused after deletion, + // so the same request deployed there by someone else must not land on the old entry. + let hash = ScriptHash(hash_script(( + &ns, + resolved_on_behalf_of.as_deref(), + &authed.username, + ))); if sqlx::query_scalar!( "SELECT 1 FROM script WHERE hash = $1 AND workspace_id = $2", hash.0, @@ -1692,8 +1699,8 @@ async fn create_script_internal<'c>( .is_some() { return Err(Error::BadRequest( - "A script with same hash (hence same path, description, summary, content) already \ - exists!" + "A version with the same hash (same content, settings, run-as identity and deployer) \ + already exists for this path." .to_owned(), )); }; @@ -2674,7 +2681,7 @@ async fn create_script_internal<'c>( .await?; let schedule = sqlx::query_as::<_, Schedule>( - "UPDATE schedule SET path = $1, script_path = $1 WHERE path = $2 AND workspace_id = $3 AND is_flow IS false RETURNING *") + "UPDATE schedule SET path = $1, script_path = $1 WHERE path = $2 AND script_path = $2 AND workspace_id = $3 AND is_flow IS false RETURNING *") .bind(&ns.path) .bind(&p_path) .bind(&w_id) @@ -3666,6 +3673,7 @@ async fn toggle_workspace_error_handler( } async fn get_tokened_raw_script_by_path( + windmill_common::client_ip::ClientIp(client_ip): windmill_common::client_ip::ClientIp, Extension(user_db): Extension, Extension(db): Extension, Extension(cache): Extension>, @@ -3673,7 +3681,7 @@ async fn get_tokened_raw_script_by_path( Query(query): Query, ) -> Result { let authed = cache - .get_authed(Some(w_id.clone()), &token) + .get_authed(Some(w_id.clone()), &token, client_ip) .await .ok_or_else(|| Error::NotAuthorized("Invalid token".to_string()))?; return raw_script_by_path( diff --git a/backend/windmill-api-settings/src/audit_logs_s3_backfill.rs b/backend/windmill-api-settings/src/audit_logs_s3_backfill.rs index 0c5c55f7ed..4f99f61868 100644 --- a/backend/windmill-api-settings/src/audit_logs_s3_backfill.rs +++ b/backend/windmill-api-settings/src/audit_logs_s3_backfill.rs @@ -344,7 +344,8 @@ async fn run_backfill( row_to_json(r)::text AS "line!" FROM ( SELECT workspace_id, id, timestamp, username, operation, - action_kind::text AS action_kind, resource, parameters, email, span + action_kind::text AS action_kind, resource, parameters, email, span, + client_ip, user_agent, peer_ip, forwarded_for FROM audit_partitioned WHERE timestamp >= $1 AND timestamp < $2 AND (timestamp, id) > ($3, $4) diff --git a/backend/windmill-api-settings/src/lib.rs b/backend/windmill-api-settings/src/lib.rs index 85d585c146..9172c72650 100644 --- a/backend/windmill-api-settings/src/lib.rs +++ b/backend/windmill-api-settings/src/lib.rs @@ -37,6 +37,9 @@ use windmill_audit::{ use windmill_common::hub_resource_types::{self, SyncSource}; use windmill_common::utils::HTTP_CLIENT_PERMISSIVE as HTTP_CLIENT; use windmill_common::DB; +use windmill_common::{ + client_ip::RequestPeer, global_settings::INSTANCE_IP_ALLOWLIST_SETTING, instance_ip_allowlist, +}; use ee_oss::validate_license_key; use windmill_common::usernames::generate_instance_username_for_all_users; @@ -149,6 +152,8 @@ pub fn global_service() -> Router { // `/envs` stays for callers that found the route in the code. .route("/local", get(get_local_settings)) .route("/envs", get(get_local_settings)) + .route("/client_ip_diagnostics", get(client_ip_diagnostics)) + .route("/client_ip_trust", get(client_ip_trust)) .route( "/global/{key}", post(set_global_setting).get(get_global_setting), @@ -802,6 +807,29 @@ pub async fn get_local_settings( Ok(Json(serde_json::Value::Object(settings))) } +/// What the server believes about the caller's own request and the proxies it has seen, so a +/// superadmin can tell whether client addresses are recorded or only the proxy's. +async fn client_ip_diagnostics( + Extension(db): Extension, + authed: ApiAuthed, + parts: axum::http::request::Parts, +) -> error::JsonResult { + require_super_admin(&db, &authed).await?; + Ok(Json(windmill_common::client_ip::diagnose( + &parts.extensions, + &parts.headers, + ))) +} + +/// Whether a whole private range is trusted as proxies, for whoever is restricting a token to IP +/// addresses: a host on that network can then claim an allowed one. Any signed-in user, not +/// anonymous callers, who would learn whether forwarding headers from inside are believed. +async fn client_ip_trust(_authed: ApiAuthed) -> Json { + Json(serde_json::json!({ + "private_ranges_trusted": windmill_common::client_ip::private_ranges_trusted() + })) +} + #[derive(serde::Deserialize)] pub struct Value { pub value: Option, @@ -847,12 +875,26 @@ async fn workspace_fairness_settings_allowed() -> bool { pub async fn set_global_setting( Extension(db): Extension, authed: ApiAuthed, + request: RequestPeer, Path(key): Path, Json(value): Json, ) -> error::Result<()> { require_super_admin(&db, &authed).await?; let value = value.value.unwrap_or(serde_json::Value::Null); - set_global_setting_internal(&db, key.clone(), value.clone()).await?; + if instance_ip_allowlist::concerns(&key) { + // Validate the value itself first, so its own error is the one reported. + run_setting_pre_write_hook(&db, &key, &value).await?; + let cleared = value.is_null() || value.as_str().is_some_and(|s| s.trim().is_empty()); + let written = + std::collections::HashMap::from([(key.clone(), (!cleared).then(|| value.clone()))]); + instance_ip_allowlist::write_checked(&db, &written, Some(&request)).await?; + run_setting_post_write_hook(&db, &key).await?; + } else { + set_global_setting_internal(&db, key.clone(), value.clone()).await?; + } + if key == INSTANCE_IP_ALLOWLIST_SETTING { + instance_ip_allowlist::log_write(Some(&value)); + } audit_setting_write(&db, &authed, &key, Some(&value), None).await } @@ -878,8 +920,18 @@ async fn audit_instance_action( pub async fn set_global_setting_internal( db: &DB, key: String, - value: serde_json::Value, + mut value: serde_json::Value, ) -> error::Result<()> { + if instance_config::contains_redacted_secret(&value) { + let current = sqlx::query_scalar::<_, serde_json::Value>( + "SELECT value FROM global_settings WHERE name = $1", + ) + .bind(&key) + .fetch_optional(db) + .await?; + instance_config::restore_redacted_secrets(&key, &mut value, current.as_ref()) + .map_err(error::Error::BadRequest)?; + } let should_bump_instance_ai_revision = key == AI_CONFIG_SETTING; let value = if key == "retention_period_secs" { instance_config::clamp_retention_period(value) @@ -996,6 +1048,14 @@ async fn run_setting_post_write_hook(db: &DB, key: &str) -> error::Result<()> { if key == WORKSPACE_ROLES_SETTING { windmill_common::roles::after_instance_roles_write(db).await?; } + // The other servers apply it on the settings change event; this one at once, so the page + // that saved it reads the new trust back. + if windmill_common::client_ip::SETTING_KEYS.contains(&key) { + windmill_common::client_ip::reload(db).await; + } + if key == INSTANCE_IP_ALLOWLIST_SETTING { + instance_ip_allowlist::reload(db).await; + } Ok(()) } @@ -1007,6 +1067,10 @@ async fn run_setting_pre_write_hook( value: &serde_json::Value, ) -> error::Result<()> { match key { + k if windmill_common::client_ip::SETTING_KEYS.contains(&k) => { + windmill_common::client_ip::validate_setting(k, value) + .map_err(|e| error::Error::BadRequest(format!("{k}: {e}")))?; + } #[cfg(feature = "oauth2")] windmill_common::global_settings::OAUTH_SETTING => { let previous = windmill_common::global_settings::load_value_from_global_settings( @@ -1304,6 +1368,10 @@ async fn run_setting_pre_write_hook( windmill_common::global_settings::parse_mcp_external_idp(Some(value)) .map_err(|e| error::Error::BadRequest(format!("{key}: {e}")))?; } + INSTANCE_IP_ALLOWLIST_SETTING => { + instance_ip_allowlist::parse_setting(Some(value)) + .map_err(|e| error::Error::BadRequest(format!("{key}: {e}")))?; + } MAX_TOKEN_EXPIRATION_DAYS_SETTING => { windmill_common::global_settings::parse_max_token_expiration_days(Some(value)) .map_err(|e| { @@ -1348,12 +1416,22 @@ async fn run_setting_pre_write_hook( // Bulk instance config endpoints // --------------------------------------------------------------------------- +/// Secrets are redacted on every settings read unless asked for by name, so that a superadmin +/// token used to inspect the configuration (by a script, a CLI run or an AI assistant) does not +/// copy every instance credential into its output. +#[derive(Deserialize)] +pub struct RevealSecrets { + #[serde(default)] + pub dangerously_reveal_secrets: bool, +} + async fn get_instance_config( Extension(db): Extension, authed: ApiAuthed, + Query(reveal): Query, ) -> JsonResult { require_super_admin(&db, &authed).await?; - let config = InstanceConfig::from_db_for_api(&db) + let config = InstanceConfig::from_db_for_api(&db, reveal.dangerously_reveal_secrets) .await .map_err(|e| error::Error::internal_err(e.to_string()))?; Ok(Json(config)) @@ -1362,9 +1440,10 @@ async fn get_instance_config( async fn get_instance_config_yaml( Extension(db): Extension, authed: ApiAuthed, + Query(reveal): Query, ) -> error::Result { require_super_admin(&db, &authed).await?; - let config = InstanceConfig::from_db_for_api(&db) + let config = InstanceConfig::from_db_for_api(&db, reveal.dangerously_reveal_secrets) .await .map_err(|e| error::Error::internal_err(e.to_string()))?; let yaml = config @@ -1379,17 +1458,30 @@ async fn get_instance_config_yaml( async fn set_instance_config( Extension(db): Extension, authed: ApiAuthed, + request: RequestPeer, Json(desired): Json, ) -> error::Result<()> { require_super_admin(&db, &authed).await?; + apply_instance_config(&db, &authed, &request, desired).await +} - let current = InstanceConfig::from_db(&db) +async fn apply_instance_config( + db: &DB, + authed: &ApiAuthed, + request: &RequestPeer, + desired: InstanceConfig, +) -> error::Result<()> { + let current = InstanceConfig::from_db(db) .await .map_err(|e| error::Error::internal_err(e.to_string()))?; - let desired_map = desired.global_settings.to_settings_map(); + let mut desired_map = desired.global_settings.to_settings_map(); if !desired_map.is_empty() { let current_map = current.global_settings.to_settings_map(); + for (key, value) in desired_map.iter_mut() { + instance_config::restore_redacted_secrets(key, value, current_map.get(key)) + .map_err(error::Error::BadRequest)?; + } let mut settings_diff = instance_config::diff_global_settings(¤t_map, &desired_map, ApplyMode::Merge); let ai_config_changed = settings_diff @@ -1431,7 +1523,13 @@ async fn set_instance_config( run_setting_pre_write_hook(&db, WORKSPACE_ROLES_SETTING, &serde_json::Value::Null) .await?; } - let auditor = InstanceConfigAuditor { db: &db, author: &authed, source: None }; + let ip_allowlist_written = instance_ip_allowlist::take_concerned(&mut settings_diff); + instance_ip_allowlist::write_checked(db, &ip_allowlist_written, Some(request)).await?; + let auditor = InstanceConfigAuditor { db, author: authed, source: None }; + for (key, value) in &ip_allowlist_written { + instance_config::ConfigWriteObserver::setting_written(&auditor, key, value.as_ref()) + .await?; + } // The external-instance write removes its own key from the diff. windmill_common::external_instance_pg::write_external_instance_pg_from_diff( &db, @@ -1446,11 +1544,15 @@ async fn set_instance_config( if ai_config_changed { bump_instance_ai_config_revision(); } + if let Some(v) = ip_allowlist_written.get(INSTANCE_IP_ALLOWLIST_SETTING) { + instance_ip_allowlist::log_write(v.as_ref()); + } for key in settings_diff .upserts .iter() .map(|(k, _)| k) .chain(settings_diff.deletes.iter()) + .chain(ip_allowlist_written.keys()) { run_setting_post_write_hook(&db, key).await?; } @@ -1482,7 +1584,7 @@ async fn set_instance_config( instance_config::apply_configs_diff( &db, &configs_diff, - &InstanceConfigAuditor { db: &db, author: &authed, source: None }, + &InstanceConfigAuditor { db, author: authed, source: None }, ) .await .map_err(|e| error::Error::internal_err(e.to_string()))?; @@ -1495,6 +1597,7 @@ pub async fn get_global_setting( Extension(db): Extension, authed: ApiAuthed, Path(key): Path, + Query(reveal): Query, ) -> JsonResult { if !key.starts_with("default_error_handler_") && !key.starts_with("default_recovery_handler_") @@ -1539,7 +1642,11 @@ pub async fn get_global_setting( .await? .map(|x| x.value); - Ok(Json(value.unwrap_or_else(|| serde_json::Value::Null))) + let mut value = value.unwrap_or(serde_json::Value::Null); + if !reveal.dangerously_reveal_secrets { + instance_config::redact_setting_secrets(&key, &mut value); + } + Ok(Json(value)) } #[cfg(feature = "enterprise")] @@ -1572,6 +1679,7 @@ async fn github_app_stale_webhooks( async fn list_global_settings( Extension(db): Extension, authed: ApiAuthed, + Query(reveal): Query, ) -> JsonResult> { require_super_admin(&db, &authed).await?; let settings = sqlx::query_as!(GlobalSetting, "SELECT name, value FROM global_settings") @@ -1579,6 +1687,12 @@ async fn list_global_settings( .await? .into_iter() .filter(|s| !instance_config::is_withheld_server_secret(&s.name)) + .map(|mut s| { + if !reveal.dangerously_reveal_secrets { + instance_config::redact_setting_secrets(&s.name, &mut s.value); + } + s + }) .collect(); Ok(Json(settings)) @@ -2064,7 +2178,12 @@ async fn create_external_instance_pg_database( let tag = body.tag.as_deref().unwrap_or("datatable"); let mut tx = db.begin().await?; windmill_common::external_instance_pg::create_external_instance_database_unchecked( - &db, &mut tx, &dbname, tag, None, + &db, + &mut tx, + &dbname, + tag, + None, + &[], ) .await?; tx.commit().await?; diff --git a/backend/windmill-api-users/Cargo.toml b/backend/windmill-api-users/Cargo.toml index cfd683434c..a0af0994a7 100644 --- a/backend/windmill-api-users/Cargo.toml +++ b/backend/windmill-api-users/Cargo.toml @@ -24,6 +24,10 @@ windmill-audit.workspace = true windmill-git-sync.workspace = true argon2.workspace = true +base32.workspace = true +hmac.workspace = true +rand.workspace = true +sha1.workspace = true axum.workspace = true chrono.workspace = true http.workspace = true diff --git a/backend/windmill-api-users/src/lib.rs b/backend/windmill-api-users/src/lib.rs index ee5369e616..fd294db72d 100644 --- a/backend/windmill-api-users/src/lib.rs +++ b/backend/windmill-api-users/src/lib.rs @@ -1,3 +1,7 @@ +pub mod totp; +#[cfg(feature = "private")] +pub mod totp_ee; +mod totp_oss; pub mod users; #[cfg(feature = "private")] pub mod users_ee; diff --git a/backend/windmill-api-users/src/totp.rs b/backend/windmill-api-users/src/totp.rs new file mode 100644 index 0000000000..c2926a57ad --- /dev/null +++ b/backend/windmill-api-users/src/totp.rs @@ -0,0 +1,27 @@ +//! Native TOTP second factor for password logins. The implementation is in `totp_ee`. + +#[cfg(feature = "private")] +pub use crate::totp_ee::{ + begin_setup, check_login_code, finish_setup, notify, service, TotpChange, +}; +#[cfg(not(feature = "private"))] +pub use crate::totp_oss::{ + begin_setup, check_login_code, finish_setup, notify, service, TotpChange, +}; + +pub const TOTP_REQUIRED: &str = "Two-factor code required"; +pub const TOTP_INVALID: &str = "Invalid two-factor code"; +pub const TOTP_SETUP_REQUIRED: &str = "Two-factor setup required"; + +#[derive(serde::Serialize)] +pub struct TotpSetup { + pub secret: String, + pub otpauth_url: String, +} + +/// Whether every password login must have a second factor. Enterprise only: a build without +/// it lets a single account enroll, so it could not satisfy the requirement. +pub fn required() -> bool { + cfg!(all(feature = "enterprise", feature = "private")) + && windmill_common::global_settings::REQUIRE_TOTP.load(std::sync::atomic::Ordering::Relaxed) +} diff --git a/backend/windmill-api-users/src/totp_oss.rs b/backend/windmill-api-users/src/totp_oss.rs new file mode 100644 index 0000000000..e7557887f2 --- /dev/null +++ b/backend/windmill-api-users/src/totp_oss.rs @@ -0,0 +1,51 @@ +#[cfg(not(feature = "private"))] +use windmill_common::error::{Error, Result}; + +#[cfg(not(feature = "private"))] +fn unavailable() -> Result { + Err(Error::BadRequest( + "Two-factor authentication requires a build with the private feature".to_string(), + )) +} + +#[cfg(not(feature = "private"))] +pub fn service() -> axum::Router { + axum::Router::new() +} + +#[cfg(not(feature = "private"))] +pub async fn check_login_code( + _tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + _db: &windmill_common::DB, + _email: &str, + _code: &str, +) -> Result { + unavailable() +} + +#[cfg(not(feature = "private"))] +pub async fn begin_setup( + _db: &windmill_common::DB, + _email: &str, +) -> Result { + unavailable() +} + +#[cfg(not(feature = "private"))] +pub async fn finish_setup( + _tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + _db: &windmill_common::DB, + _email: &str, + _code: &str, + _author: &windmill_common::audit::AuditAuthor, +) -> Result>> { + unavailable() +} + +#[cfg(not(feature = "private"))] +pub enum TotpChange { + Enabled, +} + +#[cfg(not(feature = "private"))] +pub fn notify(_email: &str, _change: TotpChange) {} diff --git a/backend/windmill-api-users/src/users.rs b/backend/windmill-api-users/src/users.rs index cda45ea055..4dab6a6e65 100644 --- a/backend/windmill-api-users/src/users.rs +++ b/backend/windmill-api-users/src/users.rs @@ -14,6 +14,7 @@ use std::sync::atomic::AtomicBool; use std::sync::Arc; use std::sync::LazyLock; use std::time::Duration; +use windmill_common::client_ip::{AttributedClientIp, ClientIp}; use windmill_api_auth::ApiAuthed; @@ -124,6 +125,7 @@ pub fn global_service() -> Router { .route("/exists/{email}", get(exists_email)) .route("/email", get(get_email)) .route("/whoami", get(global_whoami)) + .nest("/totp", crate::totp::service()) .route("/list_invites", get(list_invites)) .route("/decline_invite", post(decline_invite)) .route("/accept_invite", post(accept_invite)) @@ -139,11 +141,28 @@ pub fn global_service() -> Router { "/tokens/update_scopes/{token_prefix}", post(update_token_scopes), ) + .route( + "/tokens/update_limits/{token_prefix}", + post(update_token_limits), + ) .route( "/tokens/update_label/{token_prefix}", post(update_token_label), ) .route("/tokens/list", get(list_tokens)) + .route("/tokens/risk_counts", get(token_risk_counts)) + .route( + "/tokens/risk_counts_as_super_admin", + get(token_risk_counts_as_super_admin), + ) + .route( + "/tokens/list_as_super_admin", + get(list_tokens_as_super_admin), + ) + .route( + "/tokens/delete_as_super_admin/{email}/{token_prefix}", + delete(delete_token_as_super_admin), + ) .route("/tokens/impersonate", post(impersonate)) .route("/login_links", post(create_login_link)) .route( @@ -170,6 +189,8 @@ pub fn global_service() -> Router { pub fn make_unauthed_service() -> Router { Router::new() .route("/login", post(login)) + .route("/login/totp/setup", post(login_totp_setup)) + .route("/login/totp/enable", post(login_totp_enable)) .route("/logout", post(logout).get(logout)) .route("/is_first_time_setup", get(is_first_time_setup)) .route("/request_password_reset", post(request_password_reset)) @@ -332,6 +353,11 @@ pub struct TruncatedToken { pub scopes: Option>, pub workspace_id: Option, pub read_only: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub allowed_ips: Option>, + pub admin: bool, + pub super_admin: bool, + pub risks: Vec, } // NewToken is re-exported from windmill-api-auth above @@ -340,6 +366,8 @@ pub struct TruncatedToken { pub struct Login { pub email: String, pub password: String, + #[serde(default)] + pub totp_code: Option, } lazy_static::lazy_static! { @@ -742,14 +770,20 @@ async fn logout( } async fn is_valid_logout_redirect(rd: &str) -> bool { - // Allow relative paths (same-origin redirects) - if rd.starts_with('/') && !rd.starts_with("//") { - return true; + if rd.starts_with('/') { + return same_origin_rd(Some(rd.to_string())).is_some(); + } + if rd.chars().any(|c| c.is_ascii_control()) { + return false; } let parsed = match url::Url::parse(rd) { Ok(u) => u, Err(_) => return false, }; + // Before the host check: `javascript://windmill.dev/...` has host `windmill.dev`. + if !matches!(parsed.scheme(), "http" | "https") { + return false; + } let host: &str = match parsed.host_str() { Some(h) => h, None => return false, @@ -774,8 +808,17 @@ async fn whoami( authed: ApiAuthed, ) -> JsonResult { let is_guest = windmill_api_auth::scopes::has_guest_sentinel(authed.scopes.as_deref()); - let ApiAuthed { username, email, is_admin, is_operator, groups, folders, mcp_client, .. } = - authed; + let ApiAuthed { + username, + email, + is_admin, + is_operator, + groups, + folders, + mcp_client, + super_admin_withheld, + .. + } = authed; // A guest would otherwise fall through to the non-member branch below and be // handed a `superadmin` role. Answer it here, as the operator-shaped identity it is. if is_guest { @@ -806,8 +849,14 @@ async fn whoami( if let Some(user) = user.filter(|u| u.email == email) { // The frontend gates pages on `operator`, so it reports what `caller_capabilities` // decides rather than the raw column: an admin (or superadmin) whose row still carries - // `operator` holds everything. - let user = UserInfo { operator: is_operator && !is_admin, ..user }; + // `operator` holds everything. Admin and superadmin are the credential's, which a token + // may withhold. + let user = UserInfo { + operator: is_operator && !is_admin, + is_admin, + is_super_admin: user.is_super_admin && !super_admin_withheld, + ..user + }; // An external MCP token brings its own groups, which the request and the jobs it starts // act with, so report those rather than the stored memberships. if mcp_client.is_some() { @@ -855,7 +904,7 @@ async fn whoami( async fn global_whoami( Extension(db): Extension, - ApiAuthed { email, .. }: ApiAuthed, + ApiAuthed { email, super_admin_withheld, .. }: ApiAuthed, Tokened { token }: Tokened, ) -> JsonResult { let user = sqlx::query_as!( @@ -869,7 +918,11 @@ async fn global_whoami( .map_err(|e| Error::internal_err(format!("fetching global identity: {e:#}")))?; if let Some(user) = user { - Ok(Json(user)) + // The credential's rights, which a token may withhold. + Ok(Json(GlobalUserInfo { + super_admin: user.super_admin && !super_admin_withheld, + ..user + })) } else if std::env::var("SUPERADMIN_SECRET").ok() == Some(token) { Ok(Json(GlobalUserInfo { email: email.clone(), @@ -1278,6 +1331,14 @@ async fn join_workspace<'c>( ))); } + windmill_common::workspaces::check_new_member_sso( + &mut *tx, + &w_id, + &authed.email, + Some(&username), + ) + .await?; + sqlx::query!( "INSERT INTO usr (workspace_id, email, username, is_admin, operator) @@ -1555,6 +1616,13 @@ async fn update_user( forbid_superadmin_job_token(&db, &authed.email, job_id).await?; let mut tx = db.begin().await?; + // What this request changes, for the audit entry: a super-admin grant must be visible in the + // audit log (and its stdout/OTEL copy), not just a parameterless "users.update". + let audit_super_admin = eu.is_super_admin.map(|b| b.to_string()); + let audit_devops = eu.is_devops.map(|b| b.to_string()); + let audit_disabled = eu.disabled.map(|b| b.to_string()); + let audit_name_changed = eu.name.is_some(); + let mut new_super_admin: Option = None; if let Some(sa) = eu.is_super_admin { sqlx::query_scalar!( @@ -1594,10 +1662,10 @@ async fn update_user( ) .execute(&mut *tx) .await?; - // Update super_admin flag on non-session tokens (webhooks, API tokens, etc.) + // A demotion strips superadmin from every other token; a promotion grants it to none, + // since a token carries superadmin rights only when it was minted asking for them. sqlx::query!( - "UPDATE token SET super_admin = $1 WHERE email = $2 AND label != 'session' - AND (NOT $1 OR NOT EXISTS (SELECT 1 FROM unnest(scopes) s WHERE s LIKE 'mcp:%'))", + "UPDATE token SET super_admin = false WHERE email = $2 AND label != 'session' AND NOT $1", sa, &email_to_update ) @@ -1662,8 +1730,7 @@ async fn update_user( .execute(&mut *tx) .await?; sqlx::query!( - "UPDATE token SET super_admin = $1 WHERE email = $2 AND label != 'session' - AND (NOT $1 OR NOT EXISTS (SELECT 1 FROM unnest(scopes) s WHERE s LIKE 'mcp:%'))", + "UPDATE token SET super_admin = false WHERE email = $2 AND label != 'session' AND NOT $1", sa, &email_to_update ) @@ -1710,6 +1777,19 @@ async fn update_user( } } + let mut audit_params: std::collections::HashMap<&str, &str> = std::collections::HashMap::new(); + if let Some(v) = audit_super_admin.as_deref() { + audit_params.insert("super_admin", v); + } + if let Some(v) = audit_devops.as_deref() { + audit_params.insert("devops", v); + } + if let Some(v) = audit_disabled.as_deref() { + audit_params.insert("disabled", v); + } + if audit_name_changed { + audit_params.insert("name_changed", "true"); + } audit_log( &mut *tx, &authed, @@ -1717,7 +1797,7 @@ async fn update_user( ActionKind::Update, "global", Some(&email_to_update), - None, + (!audit_params.is_empty()).then_some(audit_params), ) .await?; tx.commit().await?; @@ -2724,9 +2804,9 @@ pub async fn delete_workspace_user_internal( Ok(()) } -/// Non-admin path for `delete_workspace_user`: the creator of a fork may remove non-admin members -/// from the fork they created, so that adding the wrong collaborator is theirs to undo rather than -/// an admin's. Never on a root workspace, and never against an admin of the fork — the counterpart +/// Non-admin path for `delete_workspace_user`: the creator of a fork may remove developers from +/// the fork they created, so that adding the wrong collaborator is theirs to undo rather than an +/// admin's. Never on a root workspace, and never against any other role of the fork — the counterpart /// of the add grant, whose bounds are spelled out on `add_user` in `windmill-api-workspaces`. /// /// `target_is_admin` must come from a row locked by the caller's deletion transaction: the grant @@ -2754,6 +2834,26 @@ async fn authorize_fork_owner_delete_user( ))); } + // Only the developers the add grant could seat: removing a member an admin of the fork + // restricted would let the creator re-add them as a developer. + let target_role = sqlx::query_as::<_, (Option, bool)>( + "SELECT workspace_role, operator FROM usr WHERE workspace_id = $1 AND username = $2", + ) + .bind(w_id) + .bind(username_to_delete) + .fetch_optional(&mut **tx) + .await? + .map(|(role, operator)| windmill_common::roles::resolve_role_name(role, operator)); + if target_role + .as_deref() + .is_some_and(|r| r != windmill_common::roles::DEVELOPER_ROLE) + { + return Err(Error::PermissionDenied(format!( + "as the creator of fork {w_id} you can only remove developers; ask an admin of {w_id} \ + to remove {username_to_delete}" + ))); + } + Ok(()) } @@ -2846,6 +2946,10 @@ async fn set_login_type( .execute(&mut *tx) .await?; + if et.login_type == "password" { + windmill_common::workspaces::check_password_login_allowed(&mut *tx, &email).await?; + } + audit_log( &mut *tx, &authed, @@ -2864,13 +2968,139 @@ async fn set_login_type( )) } +struct PasswordAccount { + email: String, + super_admin: bool, + totp_enabled: bool, +} + +fn login_audit_author(email: &str) -> AuditAuthor { + AuditAuthor { + email: email.to_string(), + username: email.to_string(), + username_override: None, + token_prefix: None, + } +} + +/// The account a password login names, once its password matched, with the transaction the +/// login continues in. A mismatch and an unknown email fail alike, and count against the login +/// rate limit, which is checked before any connection is taken. +async fn verify_password_login<'c>( + db: &DB, + client_ip: Option, + argon2: &Argon2<'_>, + email: &str, + password: &str, +) -> Result<(Transaction<'c, Postgres>, PasswordAccount)> { + if windmill_common::global_settings::DISABLE_PASSWORD_LOGIN + .load(std::sync::atomic::Ordering::Relaxed) + { + return Err(Error::BadRequest( + "Password login is disabled on this instance".to_string(), + )); + } + + windmill_common::login_rate_limit::check_and_increment_login_attempt(client_ip, email)?; + + let mut tx = db.begin().await?; + let row: Option<(String, String, bool, bool)> = sqlx::query_as( + "SELECT email, password_hash, super_admin, totp_secret IS NOT NULL FROM password \ + WHERE email = $1 AND login_type = 'password' AND disabled = false", + ) + .bind(email) + .fetch_optional(&mut *tx) + .await?; + + match row { + Some((email, hash, super_admin, totp_enabled)) + if argon2 + .verify_password(password.as_bytes(), hash.as_str()) + .is_ok() => + { + Ok((tx, PasswordAccount { email, super_admin, totp_enabled })) + } + _ => { + audit_log( + &mut *tx, + &login_audit_author(email), + "users.login_failure", + ActionKind::Create, + "global", + None, + None, + ) + .await?; + windmill_common::login_rate_limit::record_login_failure(email); + Err(Error::BadRequest("Invalid login".to_string())) + } + } +} + +/// Audits a wrong two-factor code and commits, unlike a wrong password: the transaction holds +/// the wrong-code count, and a guessed code must leave a trace. +async fn reject_totp_code(mut tx: Transaction<'_, Postgres>, email: &str) -> Error { + let committed = async { + audit_log( + &mut *tx, + &login_audit_author(email), + "users.login_failure", + ActionKind::Create, + "global", + None, + Some([("reason", "invalid_totp_code")].into()), + ) + .await?; + tx.commit().await?; + Ok::<_, Error>(()) + } + .await; + if let Err(e) = committed { + return e; + } + windmill_common::login_rate_limit::record_login_failure(email); + Error::BadRequest(crate::totp::TOTP_INVALID.to_string()) +} + +async fn start_password_session( + mut tx: Transaction<'_, Postgres>, + account: &PasswordAccount, + cookies: Cookies, +) -> Result { + let token = create_session_token( + &account.email, + account.super_admin, + None, + false, + &mut tx, + cookies, + ) + .await?; + let audit_author = AuditAuthor { + token_prefix: Some(safe_token_prefix(&token)), + ..login_audit_author(&account.email) + }; + audit_log( + &mut *tx, + &audit_author, + "users.login", + ActionKind::Create, + "global", + Some(&truncate_token(&token)), + None, + ) + .await?; + tx.commit().await?; + Ok(token) +} + #[allow(unreachable_code, unused_variables)] async fn login( - headers: axum::http::HeaderMap, + AttributedClientIp(client_ip): AttributedClientIp, cookies: Cookies, Extension(db): Extension, Extension(argon2): Extension>>, - Json(Login { email, password }): Json, + Json(Login { email, password, totp_code }): Json, ) -> Result { // In `--no-auth` mode there is no real login; the frontend never needs a // session cookie because every request already resolves as the admin @@ -2880,88 +3110,95 @@ async fn login( } let email = email.to_lowercase(); + let (mut tx, account) = + verify_password_login(&db, client_ip, &argon2, &email, &password).await?; - if windmill_common::global_settings::DISABLE_PASSWORD_LOGIN - .load(std::sync::atomic::Ordering::Relaxed) - { + // Asked only once the password matched, so whether an account has a second factor is not + // disclosed to someone who does not know its password. + if account.totp_enabled { + let Some(code) = totp_code.filter(|c| !c.trim().is_empty()) else { + return Err(Error::BadRequest(crate::totp::TOTP_REQUIRED.to_string())); + }; + if !crate::totp::check_login_code(&mut tx, &db, &account.email, &code).await? { + return Err(reject_totp_code(tx, &account.email).await); + } + } else if crate::totp::required() { return Err(Error::BadRequest( - "Password login is disabled on this instance".to_string(), + crate::totp::TOTP_SETUP_REQUIRED.to_string(), )); } + start_password_session(tx, &account, cookies).await +} - windmill_common::login_rate_limit::check_and_increment_login_attempt(&headers, &email)?; - - let mut tx = db.begin().await?; - let audit_author = AuditAuthor { - email: email.clone(), - username: email.clone(), - username_override: None, - token_prefix: None, - }; - let email_w_h: Option<(String, String, bool)> = sqlx::query_as( - "SELECT email, password_hash, super_admin FROM password WHERE email = $1 AND login_type = \ - 'password' AND disabled = false", - ) - .bind(&email) - .fetch_optional(&mut *tx) - .await?; - - if let Some((email, hash, super_admin)) = email_w_h { - if argon2 - .verify_password(password.as_bytes(), hash.as_str()) - .is_err() - { - audit_log( - &mut *tx, - &audit_author, - "users.login_failure", - ActionKind::Create, - "global", - None, - None, - ) - .await?; - windmill_common::login_rate_limit::record_login_failure(&email); - Err(Error::BadRequest("Invalid login".to_string())) - } else { - let token = - create_session_token(&email, super_admin, None, false, &mut tx, cookies).await?; - - let audit_author = AuditAuthor { - email: email.clone(), - username: email.clone(), - username_override: None, - token_prefix: Some(safe_token_prefix(&token)), - }; - - audit_log( - &mut *tx, - &audit_author, - "users.login", - ActionKind::Create, - "global", - Some(&truncate_token(&token)), - None, - ) - .await?; - - tx.commit().await?; - Ok(token) - } - } else { - audit_log( - &mut *tx, - &audit_author, - "users.login_failure", - ActionKind::Create, - "global", - None, - None, - ) - .await?; - windmill_common::login_rate_limit::record_login_failure(&email); - Err(Error::BadRequest("Invalid login".to_string())) +/// The account a login-time enrollment is for: one without a second factor, on an instance +/// that requires it. Anyone else enrolls from their settings, inside a session. +async fn verify_login_enrollment<'c>( + db: &DB, + client_ip: Option, + argon2: &Argon2<'_>, + email: &str, + password: &str, +) -> Result<(Transaction<'c, Postgres>, PasswordAccount)> { + let (tx, account) = verify_password_login(db, client_ip, argon2, email, password).await?; + if account.totp_enabled || !crate::totp::required() { + return Err(Error::BadRequest( + "Two-factor setup at login is only for accounts that must enroll".to_string(), + )); } + Ok((tx, account)) +} + +#[derive(Deserialize)] +struct LoginTotpSetup { + email: String, + password: String, +} + +async fn login_totp_setup( + AttributedClientIp(client_ip): AttributedClientIp, + Extension(db): Extension, + Extension(argon2): Extension>>, + Json(LoginTotpSetup { email, password }): Json, +) -> JsonResult { + let email = email.to_lowercase(); + let (tx, account) = verify_login_enrollment(&db, client_ip, &argon2, &email, &password).await?; + drop(tx); + Ok(Json(crate::totp::begin_setup(&db, &account.email).await?)) +} + +#[derive(Deserialize)] +struct LoginTotpEnable { + email: String, + password: String, + code: String, +} + +#[derive(Serialize)] +struct LoginRecoveryCodes { + recovery_codes: Vec, +} + +/// Turns the second factor on and starts the session in one step, so the account is never +/// left logged in without it. +async fn login_totp_enable( + AttributedClientIp(client_ip): AttributedClientIp, + cookies: Cookies, + Extension(db): Extension, + Extension(argon2): Extension>>, + Json(LoginTotpEnable { email, password, code }): Json, +) -> JsonResult { + let email = email.to_lowercase(); + let (mut tx, account) = + verify_login_enrollment(&db, client_ip, &argon2, &email, &password).await?; + let author = login_audit_author(&account.email); + let Some(recovery_codes) = + crate::totp::finish_setup(&mut tx, &db, &account.email, &code, &author).await? + else { + return Err(reject_totp_code(tx, &account.email).await); + }; + start_password_session(tx, &account, cookies).await?; + crate::totp::notify(&account.email, crate::totp::TotpChange::Enabled); + Ok(Json(LoginRecoveryCodes { recovery_codes })) } #[derive(Deserialize)] @@ -2987,6 +3224,33 @@ async fn refresh_token( .to_string(), )); } + // A session carries no IP restriction, so exchanging for one would lift it. + if authed.allowed_ips.is_some() { + return Err(Error::NotAuthorized( + "A token restricted to IP addresses cannot be exchanged for a session".to_string(), + )); + } + // A session carries every right of the account, so a token withholding some may not be + // exchanged for one while the account holds them. + if authed.admin_withheld || authed.super_admin_withheld { + let lifts_withheld = sqlx::query_scalar!( + "SELECT ($2 AND EXISTS(SELECT 1 FROM usr WHERE email = $1 AND is_admin)) + OR ($3 AND COALESCE((SELECT super_admin FROM password WHERE email = $1), false))", + &authed.email, + authed.admin_withheld, + authed.super_admin_withheld, + ) + .fetch_one(&db) + .await? + .unwrap_or(true); + if lifts_withheld { + return Err(Error::NotAuthorized( + "A token without its owner's admin or superadmin rights cannot be exchanged for \ + a session" + .to_string(), + )); + } + } let t_hash = windmill_common::auth::hash_token(&token); // Only a live, non-impersonation row may be exchanged for a session: an impersonation must // end at its 24h expiry, not become a renewable service-account session billed as active. @@ -3019,13 +3283,21 @@ async fn refresh_token( let mut tx = db.begin().await?; - let super_admin = sqlx::query_scalar!( - "SELECT super_admin FROM password WHERE email = $1 AND disabled = false", + let account = sqlx::query!( + "SELECT super_admin, login_type = 'password' AND totp_secret IS NULL AS \"lacks_totp!\" + FROM password WHERE email = $1 AND disabled = false", &authed.email ) .fetch_optional(&mut *tx) - .await? - .unwrap_or(false); + .await?; + // A session from before the instance required a second factor is not renewed, so it ends + // within one session lifetime and the next login goes through the setup. + if crate::totp::required() && account.as_ref().is_some_and(|a| a.lacks_totp) { + return Err(Error::BadRequest( + crate::totp::TOTP_SETUP_REQUIRED.to_string(), + )); + } + let super_admin = account.is_some_and(|a| a.super_admin); let new_token = create_session_token( &authed.email, @@ -3109,8 +3381,8 @@ pub async fn create_session_token<'c>( sqlx::query!( "INSERT INTO token - (token_hash, token_prefix, token, email, label, expiration, super_admin, scopes, read_only) - VALUES ($1, $2, $3, $4, $5, now() + ($6 || ' seconds')::interval, $7, $8, $9)", + (token_hash, token_prefix, token, email, label, expiration, super_admin, scopes, read_only, admin) + VALUES ($1, $2, $3, $4, $5, now() + ($6 || ' seconds')::interval, $7, $8, $9, true)", t_hash, t_prefix, plaintext as Option<&str>, @@ -3204,8 +3476,8 @@ pub async fn create_guest_session_token<'c>( sqlx::query!( "INSERT INTO token - (token_hash, token_prefix, token, email, label, expiration, super_admin, scopes, workspace_id) - VALUES ($1, $2, $3, $4, $5, now() + ($6 || ' seconds')::interval, false, $7, $8)", + (token_hash, token_prefix, token, email, label, expiration, super_admin, scopes, workspace_id, admin) + VALUES ($1, $2, $3, $4, $5, now() + ($6 || ' seconds')::interval, false, $7, $8, false)", t_hash, t_prefix, plaintext as Option<&str>, @@ -3335,6 +3607,11 @@ async fn create_token( )); } + // A token asked for here carries its owner's admin and superadmin rights only when the + // request says so; server-side mints call `create_token_internal`, where `None` inherits. + token_config.super_admin = Some(token_config.super_admin.unwrap_or(false)); + token_config.admin = Some(token_config.admin.unwrap_or(false)); + windmill_api_auth::ensure_scopes_within_caller(&authed, token_config.scopes.as_deref())?; // Mirrors the MCP OAuth approve: a scoped token cannot mint superadmin access it may lack. if token_config.super_admin == Some(true) @@ -3403,6 +3680,10 @@ async fn impersonate( )); } + let allowed_ips = windmill_api_auth::token_ip_allowlist( + authed.allowed_ips.as_deref(), + new_token.allowed_ips.as_deref(), + )?; let impersonated = new_token.impersonate_email.unwrap(); let is_super_admin = sqlx::query_scalar!( @@ -3412,23 +3693,43 @@ async fn impersonate( .fetch_optional(&db) .await? .unwrap_or(false); - let expiration = cap_token_expiration(&db, &impersonated, None, new_token.expiration).await?; + // As on `tokens/create`: the impersonated account's rights are carried only when asked. + let is_super_admin = is_super_admin && new_token.super_admin == Some(true); + let expiration = cap_token_expiration( + &db, + &impersonated, + new_token.workspace_id.as_deref(), + new_token.expiration, + ) + .await?; let mut tx = db.begin().await?; - sqlx::query!( + let rows = sqlx::query!( "INSERT INTO token - (token_hash, token_prefix, token, email, label, expiration, super_admin) - VALUES ($1, $2, $3, $4, $5, $6, $7)", + (token_hash, token_prefix, token, email, label, expiration, super_admin, allowed_ips, + workspace_id, admin) + SELECT $1, $2, $3, $4, $5, $6, $7, $8::text[]::cidr[], $9, $10 + WHERE $9::varchar IS NULL OR NOT EXISTS( + SELECT 1 FROM workspace WHERE id = $9 AND deleted = true + )", t_hash, t_prefix, plaintext as Option<&str>, impersonated, new_token.label, expiration, - is_super_admin + is_super_admin, + allowed_ips.as_deref(), + new_token.workspace_id, + new_token.admin == Some(true), ) .execute(&mut *tx) .await?; + if rows.rows_affected() == 0 { + return Err(Error::BadRequest( + "Cannot create a token for an archived workspace".to_string(), + )); + } windmill_api_auth::register_token_expiry_notification( &mut *tx, @@ -3438,6 +3739,18 @@ async fn impersonate( ) .await; + let mut params = windmill_api_auth::TokenAuditGrant { + label: new_token.label.as_deref(), + expiration, + scopes: None, + workspace_id: new_token.workspace_id.as_deref(), + read_only: false, + allowed_ips: allowed_ips.as_deref(), + admin: new_token.admin == Some(true), + super_admin: is_super_admin, + } + .params(); + params.push(("impersonated", impersonated.clone())); audit_log( &mut *tx, &authed, @@ -3445,7 +3758,7 @@ async fn impersonate( ActionKind::Delete, &"global", Some(t_prefix), - Some([("impersonated", &format!("{impersonated}")[..])].into()), + Some(windmill_api_auth::audit_params(¶ms)), ) .instrument(tracing::info_span!("token", email = &impersonated)) .await?; @@ -3507,6 +3820,21 @@ mod same_origin_rd_tests { assert!(!accepts("/x\r\nSet-Cookie: a=b")); assert!(!accepts("user/workspaces")); } + + #[tokio::test] + async fn logout_redirect_takes_same_origin_paths_and_web_urls_only() { + use super::is_valid_logout_redirect as ok; + assert!(ok("/user/login").await); + assert!(ok("https://app.windmill.dev/user/login").await); + assert!(!ok("/\\evil.example/").await); + assert!(!ok("/\t/evil.example/").await); + assert!(!ok("//evil.example/").await); + assert!(!ok("https://evil.example/").await); + assert!(!ok("javascript://windmill.dev/%0aalert(1)").await); + assert!(!ok("JAVASCRIPT://app.windmill.dev/%0aalert(1)").await); + assert!(!ok("data://windmill.dev/x").await); + assert!(!ok("https://app.windmill.dev/\r\nSet-Cookie: a=b").await); + } } /// Both provisioning writes reference `password(email)`; a typo'd address from the @@ -3549,6 +3877,12 @@ async fn create_login_link( ) -> Result<(StatusCode, Json)> { require_super_admin(&db, &authed).await?; forbid_superadmin_job_token(&db, &authed.email, job_id).await?; + // The link opens into a session that carries no IP restriction. + if authed.allowed_ips.is_some() { + return Err(Error::NotAuthorized( + "A token restricted to IP addresses cannot create login links".to_string(), + )); + } let email = nl.email.to_lowercase(); let rd = match nl.rd { @@ -3861,7 +4195,7 @@ struct LoginLinkQuery { } async fn consume_login_link( - headers: axum::http::HeaderMap, + AttributedClientIp(client_ip): AttributedClientIp, cookies: Cookies, Extension(db): Extension, Path(token): Path, @@ -3879,7 +4213,7 @@ async fn consume_login_link( // The account is unknown until the row is read, so only the global and per-IP tiers // apply here; a 32-char random token leaves nothing for the per-account tier to guard. windmill_common::login_rate_limit::check_and_increment_login_attempt( - &headers, + client_ip, &t_hash[..TOKEN_PREFIX_LEN], )?; @@ -3996,6 +4330,9 @@ struct ListTokenQuery { exclude_ephemeral: Option, } +/// `admin` and `super_admin` report the rights a token carries: its opt-in flag (a session +/// always opts in to superadmin) and what its owner holds, so a member's token is never +/// listed as admin because of the column's default. async fn list_tokens( Extension(db): Extension, ApiAuthed { email, .. }: ApiAuthed, @@ -4006,9 +4343,12 @@ async fn list_tokens( let rows = if query.exclude_ephemeral.unwrap_or(false) { sqlx::query_as!( TruncatedToken, - "SELECT label, token_prefix, expiration, created_at, \ - last_used_at, scopes, workspace_id, read_only FROM token WHERE email = $1 AND (label != 'ephemeral-script' OR label IS NULL) - ORDER BY created_at DESC LIMIT $2 OFFSET $3", + r#"SELECT label, token_prefix AS "token_prefix!", expiration, + created_at AS "created_at!", last_used_at AS "last_used_at!", scopes, workspace_id, + read_only AS "read_only!", allowed_ips::text[] AS allowed_ips, + admin AS "admin!", super_admin AS "super_admin!", risks AS "risks!" + FROM token_risk WHERE email = $1 AND (label != 'ephemeral-script' OR label IS NULL) + ORDER BY created_at DESC LIMIT $2 OFFSET $3"#, email, per_page as i64, offset as i64, @@ -4018,9 +4358,12 @@ async fn list_tokens( } else { sqlx::query_as!( TruncatedToken, - "SELECT label, token_prefix, expiration, created_at, \ - last_used_at, scopes, workspace_id, read_only FROM token WHERE email = $1 - ORDER BY created_at DESC LIMIT $2 OFFSET $3", + r#"SELECT label, token_prefix AS "token_prefix!", expiration, + created_at AS "created_at!", last_used_at AS "last_used_at!", scopes, workspace_id, + read_only AS "read_only!", allowed_ips::text[] AS allowed_ips, + admin AS "admin!", super_admin AS "super_admin!", risks AS "risks!" + FROM token_risk WHERE email = $1 + ORDER BY created_at DESC LIMIT $2 OFFSET $3"#, email, per_page as i64, offset as i64, @@ -4031,6 +4374,118 @@ async fn list_tokens( Ok(Json(rows)) } +/// How many tokens carry each risk of the `token_risk` view. +#[derive(Serialize, Default)] +pub struct TokenRiskCounts { + pub superadmin: i64, + pub admin: i64, + pub all_workspaces: i64, + pub never_expires: i64, + pub unused: i64, +} + +impl TokenRiskCounts { + fn from_rows(rows: Vec<(Option, Option)>) -> Self { + let mut c = Self::default(); + for (risk, n) in rows { + let n = n.unwrap_or(0); + match risk.as_deref() { + Some("superadmin") => c.superadmin = n, + Some("admin") => c.admin = n, + Some("all_workspaces") => c.all_workspaces = n, + Some("never_expires") => c.never_expires = n, + Some("unused") => c.unused = n, + _ => {} + } + } + c + } +} + +/// The caller's own counts, over all their tokens rather than one page of `tokens/list`. +async fn token_risk_counts( + Extension(db): Extension, + ApiAuthed { email, .. }: ApiAuthed, +) -> JsonResult { + let rows = sqlx::query!( + "SELECT r AS risk, count(*) AS n FROM token_risk, unnest(risks) r WHERE email = $1 GROUP BY r", + email, + ) + .fetch_all(&db) + .await?; + Ok(Json(TokenRiskCounts::from_rows( + rows.into_iter().map(|r| (r.risk, r.n)).collect(), + ))) +} + +/// Instance-wide counts, for the token review's summary. +async fn token_risk_counts_as_super_admin( + Extension(db): Extension, + authed: ApiAuthed, +) -> JsonResult { + require_super_admin(&db, &authed).await?; + let rows = + sqlx::query!("SELECT r AS risk, count(*) AS n FROM token_risk, unnest(risks) r GROUP BY r") + .fetch_all(&db) + .await?; + Ok(Json(TokenRiskCounts::from_rows( + rows.into_iter().map(|r| (r.risk, r.n)).collect(), + ))) +} + +#[derive(FromRow, Serialize)] +pub struct TokenForReview { + pub email: Option, + pub label: Option, + pub token_prefix: String, + pub expiration: Option>, + pub created_at: chrono::DateTime, + pub last_used_at: chrono::DateTime, + pub scopes: Option>, + pub workspace_id: Option, + pub read_only: bool, + pub risks: Vec, +} + +#[derive(Deserialize)] +pub struct TokenReviewQuery { + /// A risk to narrow to, `all` for every token, or none for any risk. + pub flag: Option, + pub search: Option, + pub per_page: Option, + /// The last row of the previous page. A cursor rather than an offset, since the order + /// moves as tokens are used: an offset would skip rows that move behind it. + pub after_last_used_at: Option>, + pub after_token_prefix: Option, +} + +pub(crate) fn token_review_requires_ee() -> Error { + Error::BadRequest( + "Listing and deleting every user's tokens requires a valid Windmill Enterprise Edition license" + .to_string(), + ) +} + +async fn list_tokens_as_super_admin( + Extension(db): Extension, + authed: ApiAuthed, + Query(query): Query, +) -> JsonResult> { + require_super_admin(&db, &authed).await?; + Ok(Json( + crate::users_oss::list_tokens_as_super_admin(&db, query).await?, + )) +} + +async fn delete_token_as_super_admin( + Extension(db): Extension, + authed: ApiAuthed, + Path((email, token_prefix)): Path<(String, String)>, +) -> Result { + require_super_admin(&db, &authed).await?; + crate::users_oss::delete_token_as_super_admin(&db, &authed, &email, &token_prefix).await +} + /// Ends a user's MCP OAuth connections (only those bound to `workspace_id` when given), /// including idle ones whose access token is already gone and codes not yet exchanged. /// Lock the user's `password` row before writing their tokens (see `lock_mcp_oauth_grants`). @@ -4122,37 +4577,62 @@ async fn update_token_scopes( Path(token_prefix): Path, Json(req): Json, ) -> Result { - // Widening is what makes a narrowly-scoped mint (app embed, raw-app SDK, MCP - // OAuth) recoverable as a general credential: a job token is unscoped, so the - // caller check below would let it clear the scopes of any token sharing its - // email (GHSA-hfh4-cx4h-3fcr). - forbid_elevated_job_token(&db, &authed.email, authed.job_id).await?; + // A job token is unscoped, so the caller checks below would let it widen any token + // sharing its email (GHSA-hfh4-cx4h-3fcr), and narrowing one breaks whatever holds it. + forbid_job_token_account_destruction(&authed)?; windmill_api_auth::ensure_scopes_within_caller(&authed, req.scopes.as_deref())?; let mut tx = db.begin().await?; + let token = lock_owned_token(&mut tx, &authed.email, &token_prefix).await?; // A guest-labelled token is never rescoped: its scopes are its whole confinement, // and after promotion the same email owns an account that could otherwise strip - // them from the still-valid guest credential. Same shape as the relabel guard. - let updated: Option = sqlx::query_scalar!( - "UPDATE token SET scopes = $1 - WHERE email = $2 AND token_prefix = $3 - AND (label IS NULL OR label <> 'guest_session') - RETURNING token_prefix", - req.scopes.as_deref(), - &authed.email, - &token_prefix, - ) - .fetch_optional(&mut *tx) - .await?; - - let prefix = updated.ok_or_else(|| { - Error::NotFound(format!( + // them from the still-valid guest credential. + if windmill_common::auth::is_guest_session_label(token.label.as_deref()) { + return Err(Error::NotFound(format!( "token {token_prefix} not found, not owned by user, or not rescopable" - )) - })?; + ))); + } + let widens = + windmill_api_auth::ensure_scopes_within(token.scopes.as_deref(), req.scopes.as_deref()) + .is_err(); + if widens { + // A system token is minted narrow for one purpose and handed wherever that purpose + // needs it (an app's viewers, the editor, a deploy), so widening it in place makes a + // general credential of a secret its owner never held. A sign-in the owner approved + // for an MCP client is theirs to widen. + let label = token.label.as_deref(); + if !windmill_common::auth::is_user_token(label) + && !label.is_some_and(|l| l.starts_with("mcp-oauth-")) + { + return Err(Error::BadRequest( + "the scopes of a token the server minted can only be narrowed".to_string(), + )); + } + let allowed_ips = + windmill_api_auth::token_ip_allowlist_oss::load_allowed_ips(token.allowed_ips.clone()); + windmill_api_auth::ensure_grant_within_caller( + &authed, + &windmill_api_auth::TokenGrant { + scopes: req.scopes.as_deref(), + super_admin: token.super_admin, + admin: token.admin, + allowed_ips: allowed_ips.as_deref(), + }, + )?; + } + + sqlx::query!( + "UPDATE token SET scopes = $1 WHERE token_hash = $2", + req.scopes.as_deref(), + &token.token_hash, + ) + .execute(&mut *tx) + .await?; + let prefix = token_prefix; let scopes_json = serde_json::to_string(&req.scopes).unwrap_or_default(); + let previous_json = serde_json::to_string(&token.scopes).unwrap_or_default(); audit_log( &mut *tx, &authed, @@ -4160,7 +4640,13 @@ async fn update_token_scopes( ActionKind::Update, &"global", Some(&prefix), - Some([("scopes", scopes_json.as_str())].into()), + Some( + [ + ("scopes", scopes_json.as_str()), + ("previous_scopes", previous_json.as_str()), + ] + .into(), + ), ) .await?; @@ -4171,6 +4657,210 @@ async fn update_token_scopes( Ok(format!("updated scopes for token {prefix}")) } +/// The grant of a token row a token edit compares the requested change against. +struct OwnedToken { + token_hash: String, + label: Option, + scopes: Option>, + super_admin: bool, + admin: bool, + allowed_ips: Option>, + expiration: Option>, + workspace_id: Option, +} + +async fn lock_owned_token( + tx: &mut Transaction<'_, Postgres>, + email: &str, + token_prefix: &str, +) -> Result { + sqlx::query_as!( + OwnedToken, + r#"SELECT token_hash, label, scopes, super_admin, admin, + allowed_ips::text[] AS allowed_ips, expiration, workspace_id + FROM token + WHERE email = $1 AND token_prefix = $2 + AND (expiration IS NULL OR expiration > now()) + FOR UPDATE"#, + email, + token_prefix, + ) + .fetch_optional(&mut **tx) + .await? + .ok_or_else(|| { + Error::NotFound(format!( + "token {token_prefix} not found or not owned by user" + )) + }) +} + +/// Deserializes a field that is present into `Some`, so `Option>` tells an absent +/// field (`None`, leave as is) from an explicit `null` (`Some(None)`, clear it). +fn present<'de, D, T>(d: D) -> std::result::Result, D::Error> +where + D: serde::Deserializer<'de>, + T: Deserialize<'de>, +{ + T::deserialize(d).map(Some) +} + +#[derive(Deserialize)] +struct UpdateTokenLimitsRequest { + #[serde(default, deserialize_with = "present")] + expiration: Option>>, + #[serde(default, deserialize_with = "present")] + allowed_ips: Option>>, +} + +/// Change when a token expires and which networks it may be used from. Tightening either is +/// always allowed; widening only to what the caller could mint through `tokens/create` now. +async fn update_token_limits( + Extension(db): Extension, + authed: ApiAuthed, + Path(token_prefix): Path, + Json(req): Json, +) -> Result { + forbid_job_token_account_destruction(&authed)?; + if req.expiration.is_none() && req.allowed_ips.is_none() { + return Err(Error::BadRequest( + "nothing to update: pass expiration or allowed_ips".to_string(), + )); + } + if let Some(Some(expiration)) = req.expiration { + if expiration <= chrono::Utc::now() { + return Err(Error::BadRequest( + "expiration must be in the future; delete the token to revoke it".to_string(), + )); + } + } + // Validated and normalized as on create, the caller's own networks applied below. + let requested_ips = match &req.allowed_ips { + None => None, + Some(None) => Some(None), + Some(Some(list)) => Some(windmill_api_auth::token_ip_allowlist(None, Some(list))?), + }; + + let mut tx = db.begin().await?; + let token = lock_owned_token(&mut tx, &authed.email, &token_prefix).await?; + // System tokens' lifetimes and reach are the server's to manage (sessions are refreshed, + // app and SDK tokens live as long as the open app, OAuth grants follow their refresh). + if !windmill_common::auth::is_user_token(token.label.as_deref()) { + return Err(Error::BadRequest( + "only the expiration and allowed IPs of a token you created can be changed".to_string(), + )); + } + + use windmill_api_auth::token_ip_allowlist_oss::load_allowed_ips; + let stored_ips = load_allowed_ips(token.allowed_ips.clone()); + let new_ips_text = match &requested_ips { + None => token.allowed_ips.clone(), + Some(ips) => ips.clone(), + }; + let new_ips = load_allowed_ips(new_ips_text.clone()); + let widens_ips = requested_ips.is_some() + && stored_ips + .as_deref() + .is_some_and(|old| !windmill_api_auth::ip_nets_within(old, new_ips.as_deref())); + + let (expiration, widens_expiration) = match req.expiration { + None => (token.expiration, false), + Some(requested) => { + let widens = match (token.expiration, requested) { + (None, _) => false, + (Some(_), None) => true, + (Some(old), Some(new)) => new > old, + }; + let expiration = if widens { + cap_token_expiration(&db, &authed.email, token.workspace_id.as_deref(), requested) + .await? + } else { + requested + }; + (expiration, widens) + } + }; + + if widens_ips || widens_expiration { + windmill_api_auth::ensure_grant_within_caller( + &authed, + &windmill_api_auth::TokenGrant { + scopes: token.scopes.as_deref(), + super_admin: token.super_admin, + admin: token.admin, + allowed_ips: new_ips.as_deref(), + }, + )?; + } + + sqlx::query!( + "UPDATE token SET expiration = $1, allowed_ips = $2::text[]::cidr[] + WHERE token_hash = $3", + expiration, + new_ips_text.as_deref(), + &token.token_hash, + ) + .execute(&mut *tx) + .await?; + // Other API servers drop their cached identity, which carries the old list, on this + // event; `invalidate_token_from_cache` below only reaches this process. + sqlx::query!( + "INSERT INTO notify_event (channel, payload) VALUES ('notify_token_invalidation', $1)", + &token_prefix, + ) + .execute(&mut *tx) + .await?; + if expiration != token.expiration { + windmill_api_auth::reset_token_expiry_notification( + &mut *tx, + &token.token_hash, + token.label.as_deref(), + expiration, + ) + .await?; + } + + let j = |v: serde_json::Value| v.to_string(); + let changed: Vec<&str> = [ + req.expiration.is_some().then_some("expiration"), + req.allowed_ips.is_some().then_some("allowed_ips"), + ] + .into_iter() + .flatten() + .collect(); + let mut params = vec![ + ("changed", j(serde_json::json!(changed))), + ("expiration", j(serde_json::json!(expiration))), + ( + "previous_expiration", + j(serde_json::json!(token.expiration)), + ), + ("allowed_ips", j(serde_json::json!(new_ips_text))), + ( + "previous_allowed_ips", + j(serde_json::json!(token.allowed_ips)), + ), + ]; + // Shortened by `max_token_expiration_days`. + if let Some(requested) = req.expiration.filter(|r| *r != expiration) { + params.push(("requested_expiration", j(serde_json::json!(requested)))); + } + audit_log( + &mut *tx, + &authed, + "users.token.update_limits", + ActionKind::Update, + &"global", + Some(&token_prefix), + Some(windmill_api_auth::audit_params(¶ms)), + ) + .await?; + tx.commit().await?; + + windmill_api_auth::invalidate_token_from_cache(&token_prefix); + + Ok(format!("updated limits for token {token_prefix}")) +} + #[derive(Deserialize)] struct UpdateTokenLabelRequest { label: Option, @@ -4213,34 +4903,38 @@ async fn update_token_label( // load-bearing labels described above. This SQL mirrors the canonical // `windmill_common::auth::is_user_token`; keep the two in sync (note the // case-insensitive `ephemeral` match). - let updated: Option = sqlx::query_scalar!( - "UPDATE token SET label = $1 - WHERE email = $2 AND token_prefix = $3 - AND (label IS NULL OR ( - label <> 'session' - AND label <> 'guest_session' - AND lower(label) NOT LIKE 'ephemeral%' - AND label <> 'debugger-token' - AND label NOT LIKE 'mcp-oauth-%' - AND NOT starts_with(label, 'embed_app:') - AND NOT starts_with(label, 'sdk_app:') - AND NOT starts_with(label, 'impersonation:') - AND NOT starts_with(label, 'cli-login:') - AND NOT starts_with(label, 'remote-deploy:') + // `old` is the row as it stood before this statement, for the audit entry. + let updated = sqlx::query!( + "UPDATE token t SET label = $1 + FROM token old + WHERE old.token_hash = t.token_hash + AND t.email = $2 AND t.token_prefix = $3 + AND (t.label IS NULL OR ( + t.label <> 'session' + AND t.label <> 'guest_session' + AND lower(t.label) NOT LIKE 'ephemeral%' + AND t.label <> 'debugger-token' + AND t.label NOT LIKE 'mcp-oauth-%' + AND NOT starts_with(t.label, 'embed_app:') + AND NOT starts_with(t.label, 'sdk_app:') + AND NOT starts_with(t.label, 'impersonation:') + AND NOT starts_with(t.label, 'cli-login:') + AND NOT starts_with(t.label, 'remote-deploy:') )) - RETURNING token_prefix", + RETURNING t.token_prefix, old.label AS previous_label", req.label.as_deref(), &authed.email, &token_prefix, ) .fetch_optional(&mut *tx) - .await?; - - let prefix = updated.ok_or_else(|| { + .await? + .ok_or_else(|| { Error::NotFound(format!( "token {token_prefix} not found, not owned by user, or not editable" )) })?; + let prefix = updated.token_prefix; + let previous_label = updated.previous_label.unwrap_or_default(); audit_log( &mut *tx, @@ -4249,7 +4943,13 @@ async fn update_token_label( ActionKind::Update, &"global", Some(&prefix), - Some([("label", req.label.as_deref().unwrap_or(""))].into()), + Some( + [ + ("label", req.label.as_deref().unwrap_or("")), + ("previous_label", previous_label.as_str()), + ] + .into(), + ), ) .await?; @@ -4324,6 +5024,7 @@ async fn get_all_runnables( Extension(db): Extension, authed: ApiAuthed, Tokened { token }: Tokened, + ClientIp(client_ip): ClientIp, Extension(cache): Extension>, ) -> JsonResult> { let mut tx = db.clone().begin(&authed).await?; @@ -4339,7 +5040,7 @@ async fn get_all_runnables( for workspace in workspaces { let nauthed = cache - .get_authed(Some(workspace.clone()), &token) + .get_authed(Some(workspace.clone()), &token, client_ip) .await .ok_or_else(|| { Error::BadRequest(format!("not authorized to access workspace: {workspace}")) @@ -4596,9 +5297,22 @@ async fn overwrite_global_users( // Replaces the account table, so — unlike the paths that remove one account — it deliberately // does not call `delete_drafts_of_email`: the addresses are about to be reinstated, and // dropping every draft on the instance to restore accounts would be pure collateral. - sqlx::query!("DELETE FROM password") - .execute(&mut *tx) - .await?; + // The export leaves TOTP secrets out, since its files end up in git. A second factor is + // kept for every account the overwrite reinstates, rather than silently switched off. + // Read by the DELETE itself: a separate snapshot would miss an enrollment committing + // between the two and then delete it. The secrets are under the `admins` key: its row lock + // keeps a rotation from re-encrypting while the restored rows are not visible to it. + sqlx::query!( + "SELECT 1 AS \"one!\" FROM workspace_key + WHERE workspace_id = 'admins' AND kind = 'cloud' FOR UPDATE" + ) + .fetch_optional(&mut *tx) + .await?; + let totp = sqlx::query!( + "DELETE FROM password RETURNING email, totp_secret, totp_last_step, totp_recovery_codes" + ) + .fetch_all(&mut *tx) + .await?; for user in users { sqlx::query!( "INSERT INTO password(email, password_hash, login_type, super_admin, verified, name, company, first_time_user, username) @@ -4616,6 +5330,18 @@ async fn overwrite_global_users( .execute(&mut *tx) .await?; } + for t in totp.into_iter().filter(|t| t.totp_secret.is_some()) { + sqlx::query!( + "UPDATE password SET totp_secret = $2, totp_last_step = $3, totp_recovery_codes = $4 + WHERE email = $1", + t.email, + t.totp_secret, + t.totp_last_step, + t.totp_recovery_codes.as_deref() + ) + .execute(&mut *tx) + .await?; + } audit_log( &mut *tx, &authed, diff --git a/backend/windmill-api-users/src/users_oss.rs b/backend/windmill-api-users/src/users_oss.rs index a1eedd8563..f33cb0a3b7 100644 --- a/backend/windmill-api-users/src/users_oss.rs +++ b/backend/windmill-api-users/src/users_oss.rs @@ -36,3 +36,23 @@ pub(crate) async fn portal_cloud_trial_login( .to_string(), )) } + +// The CE image builds with `private` but not `enterprise`, so these, not `users_ee`'s, serve +// it: the instance-wide token list stays EE. +#[cfg(not(all(feature = "private", feature = "enterprise")))] +pub(crate) async fn list_tokens_as_super_admin( + _db: &windmill_common::DB, + _query: crate::users::TokenReviewQuery, +) -> windmill_common::error::Result> { + Err(crate::users::token_review_requires_ee()) +} + +#[cfg(not(all(feature = "private", feature = "enterprise")))] +pub(crate) async fn delete_token_as_super_admin( + _db: &windmill_common::DB, + _authed: &windmill_api_auth::ApiAuthed, + _email: &str, + _token_prefix: &str, +) -> windmill_common::error::Result { + Err(crate::users::token_review_requires_ee()) +} diff --git a/backend/windmill-api-workspaces/src/datatable_clone.rs b/backend/windmill-api-workspaces/src/datatable_clone.rs index 398766b19e..28e352eadb 100644 --- a/backend/windmill-api-workspaces/src/datatable_clone.rs +++ b/backend/windmill-api-workspaces/src/datatable_clone.rs @@ -28,13 +28,13 @@ use windmill_common::workspaces::{ use windmill_common::{PgDatabase, DB}; use crate::datatable_acl::connect_with_notices; +use crate::datatable_extensions::{read_extension_plan, ExtensionPlan}; use crate::datatable_migrations::{ lock_migration_runs_on, read_applied_migrations, write_applied_migrations, AppliedMigrations, }; use crate::datatable_permissions::ensure_reaches_governing_datatable; use crate::workspaces::{ - copy_database_settings, create_database_on_server, ensure_datatable_is_clonable, - pg_dump_database, pg_import_dump, DumpFile, PgDumpOptions, + copy_database_settings, create_database_on_server, ensure_datatable_is_clonable, DumpFile, }; /// A database this request created and filled for the data tables of the fork on one source @@ -468,16 +468,16 @@ async fn make_copy( // Ownership never carries over: the restore runs as the target's connection user. Grants do, // except on a cluster Windmill manages, which plants its own and where the replay below is what // reproduces the roles'. - let dump = pg_dump_database( - &server, - PgDumpOptions { schema_only, no_owner: true, no_acl: managed, ..Default::default() }, - ) - .await?; + let extensions = read_extension_plan(db, &server, schema_only).await?; + let dump = extensions.dump(db, &server, schema_only, managed).await?; let applied = match migrations_lock { Some(client) => Some(read_applied_migrations(&client).await?), None => None, }; + // On a cluster Windmill manages, its administrator creates the copy's extensions with the + // database, before the copy's role may write to it. On a server of the workspace's own, the + // role creates them itself when the dump is restored. match source_database.resource_type { DataTableCatalogResourceType::Instance => { windmill_common::create_custom_instance_database( @@ -485,6 +485,7 @@ async fn make_copy( request.dbname, "datatable", Some(parent_w_id), + &extensions.database_extensions(), ) .await? } @@ -496,6 +497,7 @@ async fn make_copy( request.dbname, "datatable", Some(parent_w_id), + &extensions.database_extensions(), ) .await?; tx.commit().await?; @@ -515,6 +517,7 @@ async fn make_copy( &server, &target, &dump, + &extensions, applied.as_ref(), ) .await; @@ -556,9 +559,10 @@ async fn fill( source: &PgDatabase, target: &PgDatabase, dump: &DumpFile, + extensions: &ExtensionPlan, applied: Option<&AppliedMigrations>, ) -> Result { - pg_import_dump(target, dump).await?; + extensions.restore(db, dump, target).await?; if let Some(applied) = applied { write_applied_migrations(db, target, applied).await?; } diff --git a/backend/windmill-api-workspaces/src/datatable_extensions.rs b/backend/windmill-api-workspaces/src/datatable_extensions.rs new file mode 100644 index 0000000000..11b606349e --- /dev/null +++ b/backend/windmill-api-workspaces/src/datatable_extensions.rs @@ -0,0 +1,456 @@ +/* + * Author: Ruben Fiszel + * Copyright: Windmill Labs, Inc 2022 + * 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. + */ + +//! Copying a database that uses extensions. +//! +//! A copy is replayed as the target's own connection role, which can neither create an extension +//! only a superuser may create nor comment on one it does not own, and `pg_dump` writes both for +//! every extension. So the dump leaves extensions out, and the copy is given them first: by its +//! cluster's administrator when Windmill manages it, as it creates the database +//! ([`ExtensionPlan::database_extensions`]), by the target's role otherwise. +//! +//! The dump is an archive, and what of it is replayed is chosen entry by entry, by the source +//! object each entry is for ([`ExtensionPlan::skipped_entries`]). + +use std::collections::BTreeSet; +use std::io::Write; + +use windmill_common::error::{pg_error_message, Error, Result}; +use windmill_common::{DatabaseExtension, PgDatabase, DB}; + +use crate::workspaces::{ + pg_dump_database, pg_import_dump, pg_restore_list, pg_restore_script, DumpFile, PgDumpOptions, +}; + +const TIMESCALEDB: &str = "timescaledb"; + +/// What a copy of one database needs done about the extensions it uses. +#[derive(Default)] +pub(crate) struct ExtensionPlan { + /// In creation order, so an extension comes after those it requires. + extensions: Vec, + /// Schemas holding an extension that the dump creates too. The copy needs them before its + /// extensions, so they are made first, with their comments, and the dump's `CREATE SCHEMA` and + /// `COMMENT ON SCHEMA` are not replayed: the copy's role may not own one it did not make. + extension_schemas: Vec, + /// The source objects whose archive entries are not replayed, as `(catalog oid, object oid)`. + skipped_entries: BTreeSet<(u32, u32)>, +} + +fn quote_ident(name: &str) -> String { + format!("\"{}\"", name.replace('"', "\"\"")) +} + +fn source_err(dbname: &str) -> impl FnOnce(tokio_postgres::Error) -> Error + '_ { + move |e| { + Error::internal_err(format!( + "Failed to read the extensions of database '{dbname}': {}", + pg_error_message(&e) + )) + } +} + +/// Read what copying `source` takes: its extensions. Refuses, before anything is created, what a +/// copy cannot carry. +pub(crate) async fn read_extension_plan( + db: &DB, + source: &PgDatabase, + schema_only: bool, +) -> Result { + let (client, connection) = source.connect(Some(db)).await?; + let join_handle = tokio::spawn(async move { connection.await }); + let plan = read_plan(&client, &source.dbname, schema_only).await; + drop(client); + windmill_common::shutdown_pg_connection(join_handle).await?; + plan +} + +async fn read_plan( + client: &tokio_postgres::Client, + dbname: &str, + schema_only: bool, +) -> Result { + // An extension's schema is dumped unless it is Postgres's own, `public`, which every database + // already has, or one an extension created as part of itself. + let rows = client + .query( + "SELECT e.extname::text, n.nspname::text, + n.nspname NOT IN ('public', 'pg_catalog') AND NOT EXISTS ( + SELECT 1 FROM pg_depend d + WHERE d.classid = 'pg_namespace'::regclass AND d.objid = n.oid + AND d.deptype = 'e'), + 'pg_namespace'::regclass::oid, n.oid, obj_description(n.oid, 'pg_namespace') + FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace + WHERE e.extname <> 'plpgsql' + ORDER BY e.oid", + &[], + ) + .await + .map_err(source_err(dbname))?; + let mut plan = ExtensionPlan::default(); + let mut extension_schemas = BTreeSet::new(); + for row in rows { + let dumped_schema = row.get::<_, bool>(2); + if dumped_schema { + extension_schemas.insert(row.get::<_, String>(1)); + plan.skipped_entries.insert((row.get(3), row.get(4))); + } + plan.extensions.push(DatabaseExtension { + name: row.get(0), + schema: row.get(1), + schema_comment: if dumped_schema { row.get(5) } else { None }, + }); + } + plan.extension_schemas = extension_schemas.into_iter().collect(); + + if plan.extensions.iter().any(|e| e.name == TIMESCALEDB) { + refuse_hypertables(client, dbname).await?; + } + if !schema_only { + refuse_extension_rows(client, dbname).await?; + } + Ok(plan) +} + +/// Refuse a copy with data of a database whose extensions' configuration tables hold rows of its +/// users, such as PostGIS's custom spatial references: leaving the extensions out of the dump +/// leaves those rows out too, and the copy's role could not write them anyway. TimescaleDB's always +/// hold bookkeeping its copy in the new database writes again, and its hypertables are refused on +/// their own. +async fn refuse_extension_rows(client: &tokio_postgres::Client, dbname: &str) -> Result<()> { + // `extcondition` is the filter pg_dump applies to pick the rows that are the user's. + let tables = client + .query( + "SELECT e.extname::text, c.oid::regclass::text, COALESCE(e.extcondition[i], '') + FROM pg_extension e + CROSS JOIN LATERAL generate_subscripts(e.extconfig, 1) AS i + JOIN pg_class c ON c.oid = e.extconfig[i] + WHERE c.relkind = 'r' AND e.extname <> $1 + ORDER BY 1, 2", + &[&TIMESCALEDB], + ) + .await + .map_err(source_err(dbname))?; + let mut holding = vec![]; + for table in tables { + let (extension, relation, condition): (String, String, String) = + (table.get(0), table.get(1), table.get(2)); + let has_rows: bool = client + .query_one( + &format!("SELECT EXISTS (SELECT 1 FROM {relation} {condition})"), + &[], + ) + .await + .map_err(source_err(dbname))? + .get(0); + if has_rows { + holding.push(format!("{relation} of {extension}")); + } + } + if !holding.is_empty() { + return Err(Error::BadRequest(format!( + "Database '{dbname}' has rows of its own in tables of its extensions ({}), which a \ + copy with data cannot carry: copy its schema only", + holding.join(", ") + ))); + } + Ok(()) +} + +/// Refuse a database with TimescaleDB hypertables: their rows live in chunk tables and catalog +/// rows of TimescaleDB's, which a replay as the copy's role can neither write nor reproduce. +async fn refuse_hypertables(client: &tokio_postgres::Client, dbname: &str) -> Result<()> { + let hypertables: Vec = client + .query( + "SELECT format('%I.%I', hypertable_schema, hypertable_name) + FROM timescaledb_information.hypertables ORDER BY 1", + &[], + ) + .await + .map_err(source_err(dbname))? + .iter() + .map(|row| row.get(0)) + .collect(); + if !hypertables.is_empty() { + return Err(Error::BadRequest(format!( + "Database '{dbname}' has TimescaleDB hypertables ({}), which a copy cannot carry yet", + hypertables.join(", ") + ))); + } + Ok(()) +} + +impl ExtensionPlan { + /// The extensions a database made to be this copy is created with, on a cluster Windmill + /// manages, by its administrator. + pub(crate) fn database_extensions(&self) -> Vec { + self.extensions.clone() + } + + /// Dump `source`, the database this plan was read from, as the script [`Self::restore`] + /// replays. Extensions are left out, their dependents with them, which leaving their archive + /// entries out of the replay would not do. `no_acl` as in [`PgDumpOptions`]; ownership never + /// carries over, as the restore runs as the target's connection user. + pub(crate) async fn dump( + &self, + db: &DB, + source: &PgDatabase, + schema_only: bool, + no_acl: bool, + ) -> Result { + let filter = write_lines( + &self + .extensions + .iter() + .map(|e| format!("exclude extension {}", quote_ident(&e.name))) + .collect::>(), + )?; + let archive = pg_dump_database( + source, + PgDumpOptions { + schema_only, + archive: true, + filter: filter.as_ref().map(|f| f.path.as_path()), + ..Default::default() + }, + ) + .await?; + // A hypertable made since the plan was read would be dumped as a plain table without its + // chunks. One made after the dump's snapshot is not in the dump at all. + if self.extensions.iter().any(|e| e.name == TIMESCALEDB) { + let (client, connection) = source.connect(Some(db)).await?; + let join_handle = tokio::spawn(async move { connection.await }); + let refused = refuse_hypertables(&client, &source.dbname).await; + drop(client); + windmill_common::shutdown_pg_connection(join_handle).await?; + refused?; + } + let list = self.restore_list(&archive).await?; + pg_restore_script( + &archive, + list.as_ref().map(|l| l.path.as_path()), + true, + no_acl, + ) + .await + } + + /// The `--use-list` file replaying every entry of `archive` but the skipped ones, when any is. + async fn restore_list(&self, archive: &DumpFile) -> Result> { + if self.skipped_entries.is_empty() && self.extension_schemas.is_empty() { + return Ok(None); + } + let listing = pg_restore_list(archive).await?; + let kept = skip_entries(&listing, &self.skipped_entries, &self.extension_schemas); + write_lines(&[kept]) + } + + /// Replay `dump` into `target`: its extensions first, which its role creates when it lacks + /// one, then the dump. + /// + /// Authorization: none. Callers MUST have authorized writing to `target`. + pub(crate) async fn restore( + &self, + db: &DB, + dump: &DumpFile, + target: &PgDatabase, + ) -> Result<()> { + self.prepare_target(db, target).await?; + pg_import_dump(target, dump).await + } + + /// Give `target`, as its own role, the schemas extensions live in and the extensions it lacks. + /// A database made from a template, or by a cluster administrator, may have them already. + async fn prepare_target(&self, db: &DB, target: &PgDatabase) -> Result<()> { + if self.extensions.is_empty() { + return Ok(()); + } + let (client, connection) = target.connect(Some(db)).await?; + let join_handle = tokio::spawn(async move { connection.await }); + let prepared = self.prepare_on(&client, target).await; + drop(client); + windmill_common::shutdown_pg_connection(join_handle).await?; + prepared + } + + async fn prepare_on(&self, client: &tokio_postgres::Client, target: &PgDatabase) -> Result<()> { + let target_err = |e: tokio_postgres::Error| { + Error::internal_err(format!( + "Failed to prepare database '{}' for a copy: {}", + target.dbname, + pg_error_message(&e) + )) + }; + for schema in &self.extension_schemas { + client + .batch_execute(&format!( + "CREATE SCHEMA IF NOT EXISTS {}", + quote_ident(schema) + )) + .await + .map_err(target_err)?; + } + // The replay leaves these to the copy, as a cluster administrator may have set them. The + // server quotes the comment, so no `standard_conforming_strings` lets it end the literal. + for extension in &self.extensions { + let Some(comment) = &extension.schema_comment else { + continue; + }; + let statement: Option = client + .query_opt( + "SELECT format('COMMENT ON SCHEMA %I IS %L', $1::text, $2::text) + FROM pg_namespace + WHERE nspname = $1::text + AND obj_description(oid, 'pg_namespace') IS DISTINCT FROM $2::text", + &[&extension.schema, comment], + ) + .await + .map_err(target_err)? + .map(|row| row.get(0)); + let Some(statement) = statement else { + continue; + }; + // A schema the database already had can be another role's: the copy goes without the + // comment rather than not at all. + if let Err(e) = client.batch_execute(&statement).await { + tracing::warn!( + "Not copying the comment on schema '{}' to '{}': {}", + extension.schema, + target.dbname, + pg_error_message(&e) + ); + } + } + // Creating an extension the database has would still need the rights to. + let present: BTreeSet = client + .query("SELECT extname::text FROM pg_extension", &[]) + .await + .map_err(target_err)? + .iter() + .map(|row| row.get(0)) + .collect(); + for extension in self + .extensions + .iter() + .filter(|e| !present.contains(&e.name)) + { + client + .batch_execute(&format!( + "CREATE EXTENSION IF NOT EXISTS {} WITH SCHEMA {} CASCADE", + quote_ident(&extension.name), + quote_ident(&extension.schema) + )) + .await + .map_err(|e| { + Error::BadRequest(format!( + "The copy needs extension '{}', which its database does not have and \ + role '{}' may not create: {}. Install the extension in the server's \ + template1 database, which new databases are made from, or let the role \ + create it.", + extension.name, + target.login_name(), + pg_error_message(&e).trim_end_matches('.') + )) + })?; + } + Ok(()) + } +} + +/// `lines` in a file of their own, or none when there are no lines. +fn write_lines(lines: &[String]) -> Result> { + if lines.is_empty() { + return Ok(None); + } + let file = DumpFile::new()?; + std::fs::File::create(&file.path) + .and_then(|mut f| f.write_all(lines.join("\n").as_bytes())) + .map_err(|e| Error::internal_err(format!("Failed to write a dump's file: {e}")))?; + Ok(Some(file)) +} + +/// `listing`, as `pg_restore --list` prints it, with the entries for `skipped` objects and the +/// comments on `uncommented_schemas` commented out. An entry reads `; +/// `. A comment's entry carries no oids, and names the +/// schema it is on as pg_dump writes it, quoted only when it has to be. +fn skip_entries( + listing: &str, + skipped: &BTreeSet<(u32, u32)>, + uncommented_schemas: &[String], +) -> String { + let skip = |line: &str| -> bool { + let Some((_, entry)) = line.split_once("; ") else { + return false; + }; + let mut oids = entry.split_whitespace(); + let object = ( + oids.next().and_then(|o| o.parse().ok()), + oids.next().and_then(|o| o.parse().ok()), + ); + if let (Some(catalog), Some(oid)) = object { + if skipped.contains(&(catalog, oid)) { + return true; + } + } + let Some(commented) = entry.strip_prefix("0 0 COMMENT - SCHEMA ") else { + return false; + }; + uncommented_schemas.iter().any(|schema| { + [schema.clone(), quote_ident(schema)] + .iter() + .any(|name| commented == name || commented.starts_with(&format!("{name} "))) + }) + }; + listing + .lines() + .map(|line| { + if skip(line) { + format!(";{line}") + } else { + line.to_string() + } + }) + .collect::>() + .join("\n") +} + +#[cfg(test)] +mod tests { + use super::skip_entries; + + #[test] + fn skip_entries_comments_out_only_the_skipped_objects() { + let listing = ";\n; Archive created at 2026-11-28\n\ + 278; 1259 17838 TABLE public m postgres\n\ + 3711; 2620 17842 TRIGGER public m retired postgres\n\ + 3712; 2620 17843 TRIGGER public m audit postgres\n\ + 6459; 0 0 COMMENT - SCHEMA \"My Ext\" postgres\n\ + 6461; 0 0 COMMENT - SCHEMA extensions postgres\n\ + 6462; 0 0 COMMENT - SCHEMA extensions_old postgres\n\ + 6463; 0 0 COMMENT - EXTENSION extensions "; + let kept = skip_entries( + listing, + &[(2620, 17842)].into_iter().collect(), + &["My Ext".to_string(), "extensions".to_string()], + ); + assert_eq!( + kept.lines().collect::>(), + [ + ";", + "; Archive created at 2026-11-28", + "278; 1259 17838 TABLE public m postgres", + ";3711; 2620 17842 TRIGGER public m retired postgres", + "3712; 2620 17843 TRIGGER public m audit postgres", + ";6459; 0 0 COMMENT - SCHEMA \"My Ext\" postgres", + ";6461; 0 0 COMMENT - SCHEMA extensions postgres", + "6462; 0 0 COMMENT - SCHEMA extensions_old postgres", + "6463; 0 0 COMMENT - EXTENSION extensions ", + ] + ); + } +} diff --git a/backend/windmill-api-workspaces/src/datatable_migrations.rs b/backend/windmill-api-workspaces/src/datatable_migrations.rs index 35ea6210dd..0ea6b10621 100644 --- a/backend/windmill-api-workspaces/src/datatable_migrations.rs +++ b/backend/windmill-api-workspaces/src/datatable_migrations.rs @@ -1946,6 +1946,7 @@ async fn generate_initial_datatable_migration( exclude_tables: &["_wm_migrations"], no_owner: true, no_acl, + ..Default::default() }, ) .await?; diff --git a/backend/windmill-api-workspaces/src/lib.rs b/backend/windmill-api-workspaces/src/lib.rs index cc5a7b9ab0..4f95f5089e 100644 --- a/backend/windmill-api-workspaces/src/lib.rs +++ b/backend/windmill-api-workspaces/src/lib.rs @@ -4,6 +4,7 @@ pub mod data_metrics; pub mod datatable_acl; pub mod datatable_acl_oss; pub mod datatable_clone; +pub mod datatable_extensions; pub mod datatable_migration_scope; pub mod datatable_migrations; pub mod datatable_permissions; diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index 97bcc82cff..f06969d3d3 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -239,6 +239,7 @@ pub fn workspaced_service() -> Router { "/protection_rules/{rule_name}", post(update_protection_rule).delete(delete_protection_rule), ) + .route("/password_login_members", get(list_password_login_members)) .route("/log_feature_usage", post(log_feature_usage)) .route("/cloud_quotas", get(get_cloud_quotas)) .route("/prune_versions", post(prune_versions)) @@ -3376,28 +3377,33 @@ pub(crate) async fn resolve_pg_source_checked_with_kind( managed_kind = kind; connection } else if let Some(path) = source.strip_prefix("$res:") { - let db_with_authed = windmill_common::db::DbWithOptAuthed::from_authed( - authed, - db.clone(), - Some(user_db.clone()), - ); - let value = windmill_store::resources::get_resource_value_interpolated_internal( - &db_with_authed, - w_id, - path, - None, - None, - false, - ) - .await?; + check_scopes(authed, || format!("resources:read:{}", path))?; + if let Some(dbname) = path.strip_prefix("CUSTOM_INSTANCE_DB/") { + windmill_store::resources::custom_instance_db_value(authed, db, dbname).await? + } else { + let db_with_authed = windmill_common::db::DbWithOptAuthed::from_authed( + authed, + db.clone(), + Some(user_db.clone()), + ); + let value = windmill_store::resources::get_resource_value_interpolated_internal( + &db_with_authed, + w_id, + path, + None, + None, + false, + ) + .await?; - match value { - Some(v) => v, - None => { - return Err(Error::NotAuthorized(format!( - "Resource '{}' not found or you do not have access to it", - path - ))); + match value { + Some(v) => v, + None => { + return Err(Error::NotAuthorized(format!( + "Resource '{}' not found or you do not have access to it", + path + ))); + } } } } else { @@ -3463,7 +3469,7 @@ pub(crate) struct DumpFile { } impl DumpFile { - fn new() -> Result { + pub(crate) fn new() -> Result { let dir = std::path::Path::new("/tmp/windmill"); std::fs::create_dir_all(dir) .map_err(|e| Error::internal_err(format!("Failed to create /tmp/windmill: {}", e)))?; @@ -3508,6 +3514,11 @@ impl Drop for DumpFile { pub(crate) struct PgDumpOptions<'a> { pub(crate) schema_only: bool, pub(crate) exclude_tables: &'a [&'a str], + /// A `--filter` file of what else to leave out (pg_dump 17+). + pub(crate) filter: Option<&'a std::path::Path>, + /// Write an archive for `pg_restore` rather than a `psql` script. `no_owner` and `no_acl` then + /// apply when restoring it ([`pg_restore_script`]). + pub(crate) archive: bool, /// Leave out `ALTER ... OWNER TO`. pub(crate) no_owner: bool, /// Leave out `GRANT`, `REVOKE` and `ALTER DEFAULT PRIVILEGES`. @@ -3541,7 +3552,16 @@ fn pg_dump_command( let user = pg_db.login_name(); let mut cmd = tokio::process::Command::new("pg_dump"); - cmd.arg("--format=plain").arg("--file").arg(dump_path); + cmd.arg(if opts.archive { + "--format=custom" + } else { + "--format=plain" + }) + .arg("--file") + .arg(dump_path); + if let Some(filter) = opts.filter { + cmd.arg("--filter").arg(filter); + } if opts.schema_only { cmd.arg("--schema-only"); } @@ -3575,12 +3595,37 @@ fn pg_dump_command( Ok((cmd, root_cert)) } +/// `--filter` is pg_dump 17's: an older client would refuse it as an unknown option. +async fn ensure_pg_dump_filters() -> Result<()> { + let output = tokio::process::Command::new("pg_dump") + .arg("--version") + .output() + .await + .map_err(|e| Error::internal_err(format!("Failed to execute pg_dump: {}", e)))?; + let version = String::from_utf8_lossy(&output.stdout); + let major = version.split_whitespace().find_map(|word| { + let digits: String = word.chars().take_while(char::is_ascii_digit).collect(); + digits.parse::().ok() + }); + match major { + Some(major) if major >= 17 => Ok(()), + _ => Err(Error::BadRequest(format!( + "Copying a database that uses extensions needs pg_dump 17 or later on the Windmill \ + server, which has {}", + version.trim() + ))), + } +} + /// Run pg_dump against a PgDatabase, writing output to a temp file on disk. /// Returns a DumpFile handle; the file is deleted when the handle is dropped. pub(crate) async fn pg_dump_database( pg_db: &PgDatabase, opts: PgDumpOptions<'_>, ) -> Result { + if opts.filter.is_some() { + ensure_pg_dump_filters().await?; + } let dump_file = DumpFile::new()?; let (mut cmd, _root_cert) = pg_dump_command(pg_db, opts, &dump_file.path)?; @@ -3598,6 +3643,61 @@ pub(crate) async fn pg_dump_database( Ok(dump_file) } +/// What a [`PgDumpOptions::archive`] dump holds, one entry a line as `pg_restore --list` prints +/// it: `; `, `;` starting a comment. +pub(crate) async fn pg_restore_list(archive: &DumpFile) -> Result { + let output = tokio::process::Command::new("pg_restore") + .arg("--list") + .arg(&archive.path) + .output() + .await + .map_err(|e| Error::internal_err(format!("Failed to execute pg_restore: {}", e)))?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + return Err(Error::internal_err(format!( + "pg_restore failed: {}", + stderr + ))); + } + String::from_utf8(output.stdout) + .map_err(|e| Error::internal_err(format!("pg_restore listed a non-UTF-8 entry: {e}"))) +} + +/// A [`PgDumpOptions::archive`] dump as a script [`pg_import_dump`] replays, restricted to the +/// entries `list` keeps ([`pg_restore_list`]'s format) when given. +pub(crate) async fn pg_restore_script( + archive: &DumpFile, + list: Option<&std::path::Path>, + no_owner: bool, + no_acl: bool, +) -> Result { + let script = DumpFile::new()?; + let mut cmd = tokio::process::Command::new("pg_restore"); + cmd.arg("--file").arg(&script.path); + if let Some(list) = list { + cmd.arg("--use-list").arg(list); + } + if no_owner { + cmd.arg("--no-owner"); + } + if no_acl { + cmd.arg("--no-privileges"); + } + let output = cmd + .arg(&archive.path) + .output() + .await + .map_err(|e| Error::internal_err(format!("Failed to execute pg_restore: {}", e)))?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + return Err(Error::internal_err(format!( + "pg_restore failed: {}", + stderr + ))); + } + Ok(script) +} + /// Whether `line` still belongs to the preamble pg_dump emits before the first /// dumped object: comments, blank lines, psql meta-commands and the session `SET`s. fn is_dump_preamble_line(line: &[u8]) -> bool { @@ -4115,6 +4215,7 @@ async fn create_pg_database( &req.target_dbname, "datatable", Some(&w_id), + &[], ) .await?; } else { @@ -4123,6 +4224,7 @@ async fn create_pg_database( &req.target_dbname, "datatable", Some(&w_id), + &[], ) .await?; } @@ -4355,16 +4457,17 @@ async fn import_pg_database( } else { None }; - let dump_file = pg_dump_database( - &source_pg, - PgDumpOptions { schema_only, no_owner: true, no_acl, ..Default::default() }, - ) - .await?; + let extensions = + crate::datatable_extensions::read_extension_plan(&db, &source_pg, schema_only).await?; + let dump = extensions.dump(&db, &source_pg, schema_only, no_acl).await?; let applied = match migrations_lock { Some(client) => Some(crate::datatable_migrations::read_applied_migrations(&client).await?), None => None, }; - pg_import_dump(&target_pg, &dump_file).await?; + // The target's role creates any extension it lacks. A cluster administrator creates them only + // with a database, before anyone may write to it, and this target was created by an earlier + // request. + extensions.restore(&db, &dump, &target_pg).await?; if let Some(applied) = applied { crate::datatable_migrations::write_applied_migrations(&db, &target_pg, &applied).await?; } @@ -6907,6 +7010,9 @@ async fn set_encryption_key( &new_encryption_key, ) .await?; + if w_id == "admins" { + reencrypt_totp_secrets(&mut tx, &previous_encryption_key, &new_encryption_key).await?; + } tx.commit().await?; @@ -6945,6 +7051,45 @@ async fn set_encryption_key( return Ok(()); } +/// Two-factor secrets of password logins are kept under the `admins` workspace key. Never +/// synced, so they move to the new key even when the caller skips re-encryption: one left under +/// the old key would lock its user out. +async fn reencrypt_totp_secrets( + conn: &mut sqlx::PgConnection, + old: &windmill_common::variables::WorkspaceCrypt, + new: &windmill_common::variables::WorkspaceCrypt, +) -> Result<()> { + let rows = sqlx::query!( + "SELECT email, totp_secret, totp_pending_secret FROM password + WHERE totp_secret IS NOT NULL OR totp_pending_secret IS NOT NULL FOR UPDATE" + ) + .fetch_all(&mut *conn) + .await?; + // Left as is when it does not decrypt: dropping it would switch the second factor off. + let reencrypt = |email: &str, value: Option| { + value.map(|v| match decrypt(old, v.clone()) { + Ok(plain) => encrypt(new, &plain), + Err(e) => { + tracing::warn!("the two-factor secret of {email} does not decrypt under the current key, leaving it as is: {e}"); + v + } + }) + }; + for row in rows { + let secret = reencrypt(&row.email, row.totp_secret); + let pending = reencrypt(&row.email, row.totp_pending_secret); + sqlx::query!( + "UPDATE password SET totp_secret = $2, totp_pending_secret = $3 WHERE email = $1", + row.email, + secret, + pending + ) + .execute(&mut *conn) + .await?; + } + Ok(()) +} + /// Move the git-sync secrets the server keeps under the workspace key (stored /// repository tokens, webhook secrets) to the new key. They are never synced, so /// unlike variables they are still under the old key when the caller skips @@ -8271,13 +8416,13 @@ async fn clone_resources( let repoint = (!windmill_common::can_preserve_on_behalf_of(authed)) .then(|| username_to_permissioned_as(&authed.username)); sqlx::query!( - "INSERT INTO resource (workspace_id, path, value, description, resource_type, extra_perms, edited_at, created_by) + "INSERT INTO resource (workspace_id, path, value, description, resource_type, extra_perms, edited_at, created_by, labels) SELECT $2, path, CASE WHEN $3::text IS NOT NULL AND resource_type = 'ai_agent' AND jsonb_typeof(value) = 'object' AND value ? 'on_behalf_of' THEN jsonb_set(value, '{on_behalf_of}', to_jsonb($3::text)) ELSE value END, - description, resource_type, extra_perms, edited_at, created_by + description, resource_type, extra_perms, edited_at, created_by, labels FROM resource WHERE workspace_id = $1", source_workspace_id, @@ -8328,8 +8473,8 @@ async fn clone_variables( ) -> Result<()> { // Dispatch markers are not copied, so the fork re-arms its own handler. sqlx::query!( - "INSERT INTO variable (workspace_id, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at, value_valid_until) - SELECT $2, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at, value_valid_until + "INSERT INTO variable (workspace_id, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at, value_valid_until, labels) + SELECT $2, path, value, is_secret, description, extra_perms, account, is_oauth, expires_at, value_valid_until, labels FROM variable WHERE workspace_id = $1", source_workspace_id, @@ -8412,7 +8557,7 @@ async fn clone_scripts( dedicated_worker, ws_error_handler_muted, priority, timeout, delete_after_use, delete_after_secs, restart_unless_cancelled, concurrency_key, visible_to_runner_only, auto_kind, codebase, has_preprocessor, - on_behalf_of, on_behalf_of_email, assets, modules, job_token_scopes + on_behalf_of, on_behalf_of_email, assets, modules, job_token_scopes, labels ) SELECT $1, hash, path, parent_hashes, summary, description, content, @@ -8444,7 +8589,7 @@ async fn clone_scripts( UNION ALL SELECT 1 FROM password p WHERE p.email = on_behalf_of AND p.super_admin)) - END, on_behalf_of_email, assets, modules, job_token_scopes + END, on_behalf_of_email, assets, modules, job_token_scopes, labels FROM script WHERE workspace_id = $2"#, target_workspace_id, @@ -8847,7 +8992,7 @@ async fn clone_flows( archived, schema, extra_perms, dependency_job, tag, ws_error_handler_muted, dedicated_worker, timeout, visible_to_runner_only, concurrency_key, versions, on_behalf_of, on_behalf_of_email, lock_error_logs, - job_token_scopes + job_token_scopes, labels ) SELECT $2, path, summary, description, value, edited_by, edited_at, archived, schema, extra_perms, NULL, tag, @@ -8873,7 +9018,7 @@ async fn clone_flows( UNION ALL SELECT 1 FROM password p WHERE p.email = on_behalf_of AND p.super_admin)) - END, on_behalf_of_email, lock_error_logs, job_token_scopes + END, on_behalf_of_email, lock_error_logs, job_token_scopes, labels FROM flow WHERE workspace_id = $1", source_workspace_id, @@ -8980,7 +9125,7 @@ async fn clone_apps( let preserve_identity = windmill_common::can_preserve_on_behalf_of(authed); // Get all apps from source workspace let apps = sqlx::query!( - "SELECT id, workspace_id, path, summary, policy, versions, extra_perms, custom_path + "SELECT id, workspace_id, path, summary, policy, versions, extra_perms, custom_path, labels FROM app WHERE workspace_id = $1", source_workspace_id @@ -9017,8 +9162,8 @@ async fn clone_apps( None }; let new_app_id = sqlx::query_scalar!( - "INSERT INTO app (workspace_id, path, summary, policy, versions, extra_perms, custom_path) - VALUES ($1, $2, $3, $4, $5, $6, $7) + "INSERT INTO app (workspace_id, path, summary, policy, versions, extra_perms, custom_path, labels) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id", target_workspace_id, app.path, @@ -9027,6 +9172,7 @@ async fn clone_apps( &Vec::::new(), // Start with empty versions array app.extra_perms, custom_path, + app.labels.as_deref(), ) .fetch_one(&mut **tx) .await?; @@ -9315,8 +9461,8 @@ async fn clone_raw_apps( target_workspace_id: &str, ) -> Result<()> { sqlx::query!( - "INSERT INTO raw_app (path, version, workspace_id, summary, edited_at, data, extra_perms) - SELECT path, version, $2, summary, edited_at, data, extra_perms + "INSERT INTO raw_app (path, version, workspace_id, summary, edited_at, data, extra_perms, labels) + SELECT path, version, $2, summary, edited_at, data, extra_perms, labels FROM raw_app WHERE workspace_id = $1", source_workspace_id, @@ -10157,6 +10303,8 @@ async fn create_workspace_fork( // re-using a taken (possibly archived) fork id reports the actual // conflict instead of a misleading "maximum number of workspaces" error. check_fork_w_id_conflict(&db, &nw.id).await?; + // Before the leftover cleanups below, which act on the parent's storages and catalogs. + enforce_fork_allowed(&db, &authed, &parent_workspace_id).await?; purge_stale_fork_diff_state(&db, &nw.id).await?; // A previously deleted fork with this id may have left ducklake namespaces behind if its // physical cleanup failed after the delete committed (registry rows are the durable @@ -10180,11 +10328,16 @@ async fn create_workspace_fork( .map(|i| i.msg.as_str()) .collect(); if !blocking.is_empty() { - return Err(Error::BadRequest(format!( - "a previously deleted workspace with id '{}' left ducklake namespaces that could \ - not be cleaned up: {}; retry once the catalog is reachable again", + tracing::error!( + "creating fork {}: leftover ducklake cleanup failed: {}", nw.id, blocking.join("; ") + ); + return Err(Error::BadRequest(format!( + "a previously deleted workspace with id '{}' left ducklake namespaces that could \ + not be cleaned up (details in the server logs); retry once the catalog is \ + reachable again", + nw.id ))); } for i in &leftover_issues { @@ -10206,18 +10359,22 @@ async fn create_workspace_fork( crate::workspaces_extra::purge_fork_storages_unless_live(&db, &nw.id, leftover_storages) .await?; if !storage_issues.is_empty() { - return Err(Error::BadRequest(format!( - "a previously deleted workspace with id '{}' left objects in its fork prefix that \ - could not be deleted: {}; retry once the storage is reachable again", + tracing::error!( + "creating fork {}: leftover storage purge failed: {}", nw.id, storage_issues.join("; ") + ); + return Err(Error::BadRequest(format!( + "a previously deleted workspace with id '{}' left objects in its fork prefix that \ + could not be deleted (details in the server logs); retry once the storage is \ + reachable again", + nw.id ))); } #[cfg(not(feature = "enterprise"))] _check_nb_of_workspaces(&db).await?; - enforce_fork_allowed(&db, &authed, &parent_workspace_id).await?; enforce_isolated_forks(&db, &authed, &parent_workspace_id, &nw).await?; if nw.is_dev_workspace { @@ -11287,7 +11444,8 @@ async fn attach_dev_workspace( ) .fetch_optional(&db) .await? - .unwrap_or(false); + .unwrap_or(false) + && !authed.admin_withheld; if !is_admin_of_dev && !windmill_api_auth::is_super_admin_authed(&db, &authed).await? { return Err(Error::PermissionDenied(format!( "Attaching workspace '{dev_w_id}' as a dev requires being an admin of it (or a superadmin)" @@ -11815,7 +11973,8 @@ async fn archive_workspace( ) .fetch_optional(&db) .await? - .unwrap_or(false); + .unwrap_or(false) + && !authed.admin_withheld; if !is_prod_admin && !windmill_api_auth::is_super_admin_authed(&db, &authed).await? { return Err(Error::PermissionDenied(format!( "Archiving dev workspace '{w_id}' requires being an admin of its parent prod workspace '{prod}' (or a superadmin)" @@ -12055,6 +12214,8 @@ async fn invite_user( ))); } + windmill_common::workspaces::check_new_member_sso(&mut *tx, &w_id, &nu.email, None).await?; + sqlx::query!( "INSERT INTO workspace_invite (workspace_id, email, is_admin, operator, workspace_role) @@ -12266,6 +12427,9 @@ async fn add_user( username }; + windmill_common::workspaces::check_new_member_sso(&mut *tx, &w_id, &nu.email, Some(&username)) + .await?; + sqlx::query!( "INSERT INTO usr (workspace_id, email, username, is_admin, operator, workspace_role) @@ -12852,6 +13016,38 @@ async fn list_protection_rules( )) } +#[derive(Serialize)] +struct PasswordLoginMember { + username: String, + email: String, + groups: Vec, +} + +/// Members other than service accounts whose account signs in with a password, with their groups +/// so the caller can leave out a rule's bypassers. A `RequireSso` rule does not remove them. +async fn list_password_login_members( + authed: ApiAuthed, + Extension(db): Extension, + Path(w_id): Path, +) -> JsonResult> { + require_admin(authed.is_admin, &authed.username)?; + let members = sqlx::query_as!( + PasswordLoginMember, + r#"SELECT u.username, u.email, + COALESCE(array_agg(g.group_) FILTER (WHERE g.group_ IS NOT NULL), '{}') AS "groups!" + FROM usr u + JOIN password p ON p.email = u.email AND p.login_type = 'password' + LEFT JOIN usr_to_group g ON g.workspace_id = u.workspace_id AND g.usr = u.username + WHERE u.workspace_id = $1 AND NOT u.is_service_account + GROUP BY u.username, u.email + ORDER BY u.username"#, + &w_id, + ) + .fetch_all(&db) + .await?; + Ok(Json(members)) +} + /// Insert or replace a protection ruleset within an existing transaction. Unlike the /// `create_protection_rule` handler (which rejects an existing name), this upserts, so it is safe to /// call programmatically when designating a dev/prod pair. Callers MUST invalidate the @@ -14431,6 +14627,9 @@ async fn load_workspace_authed( credential_expiry: base_authed.credential_expiry, mcp_client: base_authed.mcp_client.clone(), capabilities: None, + allowed_ips: None, + admin_withheld: base_authed.admin_withheld, + super_admin_withheld: base_authed.super_admin_withheld, }); }; @@ -14452,7 +14651,7 @@ async fn load_workspace_authed( Ok(ApiAuthed { email: base_authed.email.clone(), username: user_row.username, - is_admin: is_super_admin || user_row.is_admin, + is_admin: is_super_admin || (user_row.is_admin && !base_authed.admin_withheld), is_operator: !user_row.is_admin && windmill_common::roles::member_is_restricted( &mut conn, @@ -14473,6 +14672,9 @@ async fn load_workspace_authed( credential_expiry: base_authed.credential_expiry, mcp_client: base_authed.mcp_client.clone(), capabilities: None, + allowed_ips: None, + admin_withheld: base_authed.admin_withheld, + super_admin_withheld: base_authed.super_admin_withheld, }) } @@ -14738,7 +14940,7 @@ async fn compare_two_scripts( ) -> Result { // Get latest script from each workspace let source_script = sqlx::query!( - "SELECT hash, created_at, content, summary, description, lock, schema + "SELECT hash, created_at, content, summary, description, lock, schema, labels FROM script WHERE workspace_id = $1 AND path = $2 AND archived = false ORDER BY created_at DESC @@ -14750,7 +14952,7 @@ async fn compare_two_scripts( .await?; let target_script = sqlx::query!( - "SELECT hash, created_at, content, summary, description, lock, schema + "SELECT hash, created_at, content, summary, description, lock, schema, labels FROM script WHERE workspace_id = $1 AND path = $2 AND archived = false ORDER BY created_at DESC @@ -14770,6 +14972,7 @@ async fn compare_two_scripts( || source.description != target.description || source.lock != target.lock || source.schema != target.schema + || labels_differ(&source.labels, &target.labels) { has_changes = true; } @@ -14793,7 +14996,7 @@ async fn compare_two_flows( ) -> Result { // Get latest flow from each workspace let source_flow = sqlx::query!( - "SELECT value, summary, description, schema + "SELECT value, summary, description, schema, labels FROM flow WHERE workspace_id = $1 AND path = $2 AND archived = false", source_workspace_id, @@ -14803,7 +15006,7 @@ async fn compare_two_flows( .await?; let target_flow = sqlx::query!( - "SELECT value, summary, description, schema + "SELECT value, summary, description, schema, labels FROM flow WHERE workspace_id = $1 AND path = $2 AND archived = false", fork_workspace_id, @@ -14820,6 +15023,7 @@ async fn compare_two_flows( || source.summary != target.summary || source.description != target.description || source.schema != target.schema + || labels_differ(&source.labels, &target.labels) { has_changes = true; } @@ -14861,7 +15065,7 @@ async fn compare_two_apps( // conversion is a change even when nothing else moved. // Get app with its latest version data from source workspace let source_app = sqlx::query!( - "SELECT app.summary, app.policy, app_version.value, app_version.raw_app + "SELECT app.summary, app.policy, app_version.value, app_version.raw_app, app.labels FROM app JOIN app_version ON app_version.id = app.versions[array_upper(app.versions, 1)] @@ -14873,7 +15077,7 @@ async fn compare_two_apps( .await?; let target_app = sqlx::query!( - "SELECT app.summary, app.policy, app_version.value, app_version.raw_app + "SELECT app.summary, app.policy, app_version.value, app_version.raw_app, app.labels FROM app JOIN app_version ON app_version.id = app.versions[array_upper(app.versions, 1)] @@ -14892,6 +15096,7 @@ async fn compare_two_apps( || without_identity(&source.policy) != without_identity(&target.policy) || source.value != target.value || source.raw_app != target.raw_app + || labels_differ(&source.labels, &target.labels) { has_changes = true; } @@ -14913,6 +15118,11 @@ fn description_differs(a: &Option, b: &Option) -> bool { a.as_deref().unwrap_or("") != b.as_deref().unwrap_or("") } +// Cleared labels are stored as NULL by some writers and `{}` by others. +fn labels_differ(a: &Option>, b: &Option>) -> bool { + a.as_deref().unwrap_or_default() != b.as_deref().unwrap_or_default() +} + async fn compare_two_resources( db: &DB, source_workspace_id: &str, @@ -14921,7 +15131,7 @@ async fn compare_two_resources( ) -> Result { // Get resource from each workspace let source_resource = sqlx::query!( - "SELECT value, description, resource_type + "SELECT value, description, resource_type, labels FROM resource WHERE workspace_id = $1 AND path = $2", source_workspace_id, @@ -14931,7 +15141,7 @@ async fn compare_two_resources( .await?; let target_resource = sqlx::query!( - "SELECT value, description, resource_type + "SELECT value, description, resource_type, labels FROM resource WHERE workspace_id = $1 AND path = $2", fork_workspace_id, @@ -14983,6 +15193,7 @@ async fn compare_two_resources( if values_differ || description_differs(&source.description, &target.description) || source.resource_type != target.resource_type + || labels_differ(&source.labels, &target.labels) { has_changes = true; } @@ -15036,7 +15247,7 @@ async fn compare_two_variables( // Get variable from each workspace let source_variable = sqlx::query!( - "SELECT value::text AS \"value!\", is_secret, description, value_valid_until + "SELECT value::text AS \"value!\", is_secret, description, value_valid_until, labels FROM variable WHERE workspace_id = $1 AND path = $2", source_workspace_id, @@ -15046,7 +15257,7 @@ async fn compare_two_variables( .await?; let target_variable = sqlx::query!( - "SELECT value::text AS \"value!\", is_secret, description, value_valid_until + "SELECT value::text AS \"value!\", is_secret, description, value_valid_until, labels FROM variable WHERE workspace_id = $1 AND path = $2", fork_workspace_id, @@ -15062,6 +15273,7 @@ async fn compare_two_variables( if source.is_secret != target.is_secret || source.description != target.description || source.value_valid_until != target.value_valid_until + || labels_differ(&source.labels, &target.labels) { has_changes = true; } else if source.value != target.value @@ -15153,7 +15365,7 @@ async fn compare_two_folders( ) -> Result { // Get folder from each workspace let source_folder = sqlx::query!( - "SELECT display_name, owners, extra_perms, summary + "SELECT display_name, owners, extra_perms, summary, labels FROM folder WHERE workspace_id = $1 AND name = $2", source_workspace_id, @@ -15163,7 +15375,7 @@ async fn compare_two_folders( .await?; let target_folder = sqlx::query!( - "SELECT display_name, owners, extra_perms, summary + "SELECT display_name, owners, extra_perms, summary, labels FROM folder WHERE workspace_id = $1 AND name = $2", fork_workspace_id, @@ -15180,6 +15392,7 @@ async fn compare_two_folders( || source.owners != target.owners || source.extra_perms != target.extra_perms || source.summary != target.summary + || labels_differ(&source.labels, &target.labels) { has_changes = true; } diff --git a/backend/windmill-api-workspaces/src/workspaces_extra.rs b/backend/windmill-api-workspaces/src/workspaces_extra.rs index 3b4fe2f45b..08ac0b5312 100644 --- a/backend/windmill-api-workspaces/src/workspaces_extra.rs +++ b/backend/windmill-api-workspaces/src/workspaces_extra.rs @@ -2337,7 +2337,13 @@ async fn resolve_res_with_fallback( match (res, res_fallback_w_id) { (Ok(v), _) => Ok(v), (Err(e), None) => Err(e), - (Err(_), Some(fb)) => { + (Err(e), Some(fb)) => { + // The registry path was chosen in the deleted fork's settings, not the fallback + // workspace's, and resolution here checks no permission: only borrow a resource + // the fallback workspace's own storage or ducklake settings already use. + if !storage_settings_name_resource(db, fb, resource_path).await? { + return Err(e); + } windmill_common::workspaces::transform_json_value_unchecked( &serde_json::Value::String(format!("$res:{resource_path}")), fb, @@ -2348,6 +2354,26 @@ async fn resolve_res_with_fallback( } } +async fn storage_settings_name_resource(db: &DB, w_id: &str, resource_path: &str) -> Result { + let settings = sqlx::query_scalar::<_, Option>( + "SELECT jsonb_build_array(large_file_storage, ducklake) FROM workspace_settings \ + WHERE workspace_id = $1", + ) + .bind(w_id) + .fetch_optional(db) + .await? + .flatten(); + fn names(v: &serde_json::Value, path: &str) -> bool { + match v { + serde_json::Value::String(s) => s.strip_prefix("$res:").unwrap_or(s) == path, + serde_json::Value::Array(a) => a.iter().any(|v| names(v, path)), + serde_json::Value::Object(o) => o.values().any(|v| names(v, path)), + _ => false, + } + } + Ok(settings.is_some_and(|s| names(&s, resource_path))) +} + /// Delete every object under the fork's data prefix in the pre-resolved storage. Requires the /// `parquet` (object store) feature; without it the metadata schema is still dropped and the /// unreachable data files are left for manual cleanup. @@ -2537,7 +2563,8 @@ async fn require_prod_admin_for_dev_workspace( ) .fetch_optional(db) .await? - .unwrap_or(false); + .unwrap_or(false) + && !authed.admin_withheld; if !is_prod_admin && !windmill_api_auth::is_super_admin_authed(db, &authed).await? { return Err(Error::PermissionDenied(format!( "Destroying dev workspace '{w_id}' or its data requires being an admin of its parent prod workspace '{prod}' (or a superadmin)" diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 5db550b129..69ae832125 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -1,7 +1,7 @@ openapi: "3.0.3" info: - version: 1.884.1 + version: 1.894.1 title: Windmill API contact: @@ -41,6 +41,26 @@ paths: schema: type: string + /client_ip: + get: + summary: get the caller's IP address + description: | + The address of the client making the request, as token IP allowlists see it: forwarding + headers are believed only from the proxies in TRUSTED_PROXIES, or, when it is unset, from + loopback and the private ranges, never from Cloudflare. Behind a proxy that is not trusted, + this is the proxy's address. Empty when the server cannot tell. + operationId: getClientIp + tags: + - settings + security: [] + responses: + "200": + description: the caller's IP address + content: + text/plain: + schema: + type: string + /health/status: get: summary: health status @@ -446,6 +466,89 @@ paths: schema: type: string + /auth/login/totp/setup: + post: + security: [] + summary: start the two-factor setup an instance requires, before a session exists + operationId: loginTotpSetup + tags: + - user + requestBody: + description: the credentials of a password account that has no second factor yet + required: true + content: + application/json: + schema: + type: object + properties: + email: + type: string + password: + type: string + required: + - email + - password + responses: + "200": + description: the secret to register in an authenticator app + content: + application/json: + schema: + type: object + properties: + secret: + type: string + otpauth_url: + type: string + required: + - secret + - otpauth_url + + /auth/login/totp/enable: + post: + security: [] + summary: turn on the second factor started by loginTotpSetup and log in + operationId: loginTotpEnable + tags: + - user + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + email: + type: string + password: + type: string + code: + type: string + required: + - email + - password + - code + responses: + "200": + description: > + Two-factor authentication is on and the session cookie is set. Returns + the recovery codes, shown only once. + headers: + Set-Cookie: + schema: + type: string + content: + application/json: + schema: + type: object + properties: + recovery_codes: + type: array + items: + type: string + required: + - recovery_codes + /auth/logout: post: security: [] @@ -674,6 +777,199 @@ paths: schema: type: string + /users/totp: + get: + summary: get whether two-factor authentication is enabled for the current user + operationId: getTotpStatus + tags: + - user + responses: + "200": + description: two-factor status + content: + application/json: + schema: + type: object + properties: + enabled: + type: boolean + required: + type: boolean + description: whether the instance requires two-factor authentication for password logins + required: + - enabled + - required + + /users/totp/setup: + post: + summary: start two-factor setup by generating a new authenticator secret + operationId: setupTotp + tags: + - user + requestBody: + description: the account's current password + required: true + content: + application/json: + schema: + type: object + properties: + password: + type: string + required: + - password + responses: + "200": + description: the secret to register in an authenticator app + content: + application/json: + schema: + type: object + properties: + secret: + type: string + otpauth_url: + type: string + required: + - secret + - otpauth_url + + /users/totp/enable: + post: + summary: enable two-factor authentication with a code from the secret generated by setup + operationId: enableTotp + tags: + - user + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + code: + type: string + required: + - code + responses: + "200": + description: two-factor authentication enabled, with its recovery codes + content: + application/json: + schema: + type: object + properties: + recovery_codes: + type: array + description: single-use codes accepted in place of an authenticator code, shown only once + items: + type: string + required: + - recovery_codes + + /users/totp/recovery_codes: + post: + summary: replace the recovery codes, with a current code or a recovery code + operationId: regenerateTotpRecoveryCodes + tags: + - user + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + code: + type: string + required: + - code + responses: + "200": + description: the new recovery codes + content: + application/json: + schema: + type: object + properties: + recovery_codes: + type: array + description: single-use codes accepted in place of an authenticator code, shown only once + items: + type: string + required: + - recovery_codes + + /users/totp/disable: + post: + summary: disable two-factor authentication with a current code or a recovery code + operationId: disableTotp + tags: + - user + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + code: + type: string + required: + - code + responses: + "200": + description: two-factor authentication disabled + content: + text/plain: + schema: + type: string + + /users/totp/reset/{user}: + post: + summary: remove the two-factor authentication of a user (require super admin) + operationId: resetTotpOfUser + tags: + - user + parameters: + - name: user + in: path + required: true + schema: + type: string + responses: + "200": + description: two-factor authentication removed + content: + text/plain: + schema: + type: string + + /users/totp/enabled: + get: + summary: list the users who have two-factor authentication (require super admin) + operationId: listTotpEnabledUsers + tags: + - user + responses: + "200": + description: the emails of the users with two-factor authentication on + content: + application/json: + schema: + type: object + properties: + required: + type: boolean + description: whether the instance requires two-factor authentication for password logins + users: + type: array + items: + type: string + required: + - required + - users + /users/set_password_of/{user}: post: summary: set password for a specific user (require super admin) @@ -1903,6 +2199,7 @@ paths: - setting parameters: - $ref: "#/components/parameters/Key" + - $ref: "#/components/parameters/DangerouslyRevealSecrets" responses: "200": description: status @@ -1990,6 +2287,48 @@ paths: application/json: schema: {} + /settings/client_ip_trust: + get: + summary: whether a whole private range is trusted as proxies + description: | + Any signed-in user. True while a whole private range is trusted as proxies (the default + with nothing configured, `private`, or a range such as 10.0.0.0/8): a host on the + instance's private network can then claim an address a token's allowlist accepts. + operationId: getClientIpTrust + tags: + - setting + responses: + "200": + description: whether a whole private range is trusted as proxies + content: + application/json: + schema: + type: object + properties: + private_ranges_trusted: + type: boolean + required: + - private_ranges_trusted + + /settings/client_ip_diagnostics: + get: + summary: what the server believes about the caller's client IP and the proxies it has seen + description: | + Superadmin only. How the server resolves the client address of this very request, which + proxies it trusts for token IP allowlists (enforced) and, when it differs by Cloudflare, for + audit entries and login rate limits (attributed), and the peers whose forwarding headers + were not believed, as seen by the server process answering. + operationId: getClientIpDiagnostics + tags: + - setting + responses: + "200": + description: client IP diagnostics + content: + application/json: + schema: + $ref: "#/components/schemas/ClientIpDiagnostics" + /settings/smtp_configured: get: summary: whether instance SMTP is configured @@ -2717,6 +3056,8 @@ paths: operationId: listGlobalSettings tags: - setting + parameters: + - $ref: "#/components/parameters/DangerouslyRevealSecrets" responses: "200": description: list of settings @@ -2760,6 +3101,8 @@ paths: operationId: getInstanceConfig tags: - setting + parameters: + - $ref: "#/components/parameters/DangerouslyRevealSecrets" responses: "200": description: full instance configuration @@ -7401,6 +7744,83 @@ paths: items: $ref: "#/components/schemas/ScopeDomain" + /tokens/introspect: + get: + summary: describe the token presenting the request + description: | + Reports what the bearer credential of this request is: its row (label, expiry, bound + workspace, scopes, carried admin rights), the identity it acts as in `workspace`, and + whether the route layer would admit it on `method` `path`. Only the presented token is + ever described. Every token may call it, whatever its scopes. + operationId: introspectToken + tags: + - token + parameters: + - name: workspace + description: workspace to resolve the token's identity in + in: query + schema: + type: string + - name: path + description: | + route to check, either a full `/api/...` path or a path relative to + `/api/w/{workspace}/` + in: query + schema: + type: string + - name: method + description: HTTP method of the route to check (GET by default) + in: query + schema: + type: string + responses: + "200": + description: what the token is and may do + content: + application/json: + schema: + $ref: "#/components/schemas/TokenIntrospection" + + /tokens/admin_reliance: + post: + summary: what a token would lose without its owner's workspace admin rights + description: | + For each workspace the caller administers among `workspace_ids` (every one when + omitted), what a token with these scopes reaches only through the caller's admin + role: folders they are not a member of, other users' items not shared with them, + resources the runnables the scopes name reference, and admin-only + actions the scopes allow. Workspaces with nothing to report are left out. Refused to + a credential that is scoped or withholds admin rights. + operationId: getTokenAdminReliance + tags: + - token + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + workspace_ids: + type: array + items: + type: string + scopes: + type: array + items: + type: string + read_only: + type: boolean + responses: + "200": + description: what each workspace would lose + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/TokenAdminReliance" + /users/tokens/create: post: summary: create token @@ -7662,6 +8082,49 @@ paths: schema: type: string + /users/tokens/update_limits/{token_prefix}: + post: + summary: update expiration and allowed IPs of an existing token (owner only) + description: | + Tightening (an earlier expiration, a narrower IP list) is always allowed on a token you + created. Widening is allowed only as far as the calling token could mint a new token + with the same rights, and a later expiration is capped by `max_token_expiration_days`. + operationId: updateTokenLimits + tags: + - user + parameters: + - name: token_prefix + in: path + required: true + schema: + type: string + requestBody: + description: fields left out are unchanged, null clears + required: true + content: + application/json: + schema: + type: object + properties: + expiration: + type: string + format: date-time + nullable: true + description: new expiration (null = never expires) + allowed_ips: + type: array + items: + type: string + nullable: true + description: IPs or CIDRs the token may be used from (null = anywhere) + responses: + "200": + description: limits updated + content: + text/plain: + schema: + type: string + /users/tokens/update_label/{token_prefix}: post: summary: update label of an existing token (owner only) @@ -7716,6 +8179,104 @@ paths: items: $ref: "#/components/schemas/TruncatedToken" + /users/tokens/risk_counts: + get: + summary: count the caller's tokens carrying each risk + operationId: getTokenRiskCounts + tags: + - user + responses: + "200": + description: count per risk, over all the caller's tokens + content: + application/json: + schema: + $ref: "#/components/schemas/TokenRiskCounts" + + /users/tokens/risk_counts_as_super_admin: + get: + summary: count every user's tokens carrying each risk (superadmin only) + operationId: getTokenRiskCountsAsSuperAdmin + tags: + - user + responses: + "200": + description: count per risk, over the whole instance + content: + application/json: + schema: + $ref: "#/components/schemas/TokenRiskCounts" + + /users/tokens/list_as_super_admin: + get: + summary: list every user's tokens, least recently used first (superadmin only, EE) + description: > + Tokens the server expires or renews on its own are left out. Pages are read with a cursor: + pass the last row's `last_used_at` and `token_prefix` to get the next page. + operationId: listTokensAsSuperAdmin + tags: + - user + parameters: + - name: flag + description: a risk to narrow to, `all` for every token, or omitted for tokens with any risk + in: query + schema: + type: string + enum: [all, superadmin, admin, all_workspaces, never_expires, unused] + - name: search + description: case-insensitive substring of the owner's email or the token's label + in: query + schema: + type: string + - name: per_page + description: rows per page, 100 by default, at most 1000 + in: query + schema: + type: integer + - name: after_last_used_at + in: query + schema: + type: string + format: date-time + - name: after_token_prefix + in: query + schema: + type: string + responses: + "200": + description: one page of tokens + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/TokenForReview" + + /users/tokens/delete_as_super_admin/{email}/{token_prefix}: + delete: + summary: delete another user's token (superadmin only, EE) + operationId: deleteTokenAsSuperAdmin + tags: + - user + parameters: + - name: email + in: path + required: true + schema: + type: string + - name: token_prefix + in: path + required: true + schema: + type: string + responses: + "200": + description: delete token + content: + text/plain: + schema: + type: string + /oidc/signing_status: get: summary: what signs OIDC tokens and the keys the JWKS serves (ee only, superadmin) @@ -8312,6 +8873,37 @@ paths: "400": description: rule with this name already exists + /w/{workspace}/workspaces/password_login_members: + get: + summary: list the members other than service accounts that sign in with a password + operationId: listPasswordLoginMembers + tags: + - workspace + parameters: + - $ref: "#/components/parameters/WorkspaceId" + responses: + "200": + description: members signing in with a password, with their groups + content: + application/json: + schema: + type: array + items: + type: object + required: + - username + - email + - groups + properties: + username: + type: string + email: + type: string + groups: + type: array + items: + type: string + /w/{workspace}/workspaces/protection_rules/{rule_name}: post: summary: update an existing protection rule @@ -8993,6 +9585,12 @@ paths: variable: $ref: "#/components/schemas/CreateVariable" description: "The variable holding this account's access token. It is created with the account, in one transaction and with the same checks as createVariable, and linked to it so it refreshes through it." + is_workspace_integration: + type: boolean + description: "Issued by the workspace's own OAuth app, with `client` naming its service (google, github, nextcloud)." + replace: + type: boolean + description: "Reconnect: swap the token and account of the existing variable at variable.path in place, keeping its sharing and description." required: - refresh_token - expires_in @@ -9751,7 +10349,7 @@ paths: - truncated /w/{workspace}/resources/mcp_tools/{path}: - get: + post: summary: get MCP tools from resource operationId: getMcpTools tags: @@ -13174,6 +13772,94 @@ paths: application/json: schema: {} + /w/{workspace}/jobs/flow/nested_approvals/{job_id}: + get: + summary: list the approvals given in runs nested under a flow run + description: > + List the approval steps that runs nested under a flow run (subflows, branch and + loop runs, at any depth) went past, with who approved or rejected each and when. + The flow run's own approval steps are not listed: they are in its flow status. + Only the runs started by a step that can hold an approval step are read: a + subflow, or a loop or branch whose steps hold one. + operationId: listNestedApprovals + tags: + - job + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: job_id + in: path + required: true + description: id of the flow run + schema: + type: string + format: uuid + responses: + "200": + description: the nested approval steps, oldest first + content: + application/json: + schema: + type: object + required: + - approvals + - more + properties: + approvals: + type: array + items: + type: object + required: + - job_id + - subflows + - step_id + - required_events + - approvers + properties: + job_id: + type: string + format: uuid + description: the nested run the step belongs to + subflows: + type: array + items: + type: string + description: > + ids of the subflow steps leading to the nested run, outermost + first. Step ids are unique across a flow, loop and branch steps + included, so the first one (or the step itself) is a step of + the flow run's own graph + step_id: + type: string + step_summary: + type: string + required_events: + type: integer + description: > + approvals the step required; fewer approvers means it timed out + and the flow continued + approvers: + type: array + items: + type: object + required: + - resume_id + - approver + properties: + resume_id: + type: integer + approver: + type: string + approved_at: + type: string + format: date-time + approved: + type: boolean + more: + type: boolean + description: > + more nested runs than are read, typically a loop with an approval in + every iteration: their approvals are on those runs' own pages + /w/{workspace}/jobs/flow/approval_step_detail/{job_id}/{step_id}: get: summary: get the approval detail of one step of a flow run @@ -13284,8 +13970,9 @@ paths: approvals: type: array description: > - approvals received. approved, value and created_at are known only - while the run is live; a finished run keeps approver names alone. + approvals received. approved and value are known only while the run is + live; a finished run keeps approver names and, for approvals recorded + since it was kept, created_at. items: type: object required: @@ -13305,6 +13992,65 @@ paths: error: description: the run's error, when status is not_resumed + /w/{workspace}/jobs/approvals/waiting: + get: + summary: list the runs waiting for an approval the caller can give + description: > + Runs suspended on an approval step the caller can approve, by the same check the + approval itself runs, newest first, excluding steps the caller already approved. A + step that does not require login is listed only to callers who can read its run. + operationId: listWaitingApprovals + tags: + - job + parameters: + - $ref: "#/components/parameters/WorkspaceId" + responses: + "200": + description: runs waiting for the caller's approval + content: + application/json: + schema: + type: object + required: [approvals, total] + properties: + approvals: + type: array + description: the most recent of the listed runs, at most 100 + items: + type: object + required: + - job_id + - started_by + - created_at + - approvals + - required_approvals + properties: + job_id: + type: string + format: uuid + description: > + the suspended flow run, the one its approval page takes: the root + run, or the branch, loop or subflow run holding the approval step + flow_path: + type: string + flow_summary: + type: string + step_summary: + type: string + started_by: + type: string + created_at: + type: string + format: date-time + approvals: + type: integer + description: approvals received so far + required_approvals: + type: integer + total: + type: integer + description: how many runs are listed in all + /w/{workspace}/jobs/job_view_token/{id}: get: summary: mint a read-only share token for a job @@ -17078,6 +17824,7 @@ paths: in: query schema: type: string + - $ref: "#/components/parameters/TablePreviewFilters" - $ref: "#/components/parameters/S3Sig" - $ref: "#/components/parameters/S3Exp" responses: @@ -17132,6 +17879,8 @@ paths: in: query schema: type: string + - $ref: "#/components/parameters/TablePreviewCsvHasHeader" + - $ref: "#/components/parameters/TablePreviewFilters" - $ref: "#/components/parameters/S3Sig" - $ref: "#/components/parameters/S3Exp" responses: @@ -17166,6 +17915,12 @@ paths: in: query schema: type: string + - name: csv_separator + in: query + schema: + type: string + - $ref: "#/components/parameters/TablePreviewCsvHasHeader" + - $ref: "#/components/parameters/TablePreviewFilters" - $ref: "#/components/parameters/S3Sig" - $ref: "#/components/parameters/S3Exp" responses: @@ -19512,6 +20267,64 @@ paths: application/json: schema: {} + /w/{workspace}/jobs_u/completed/get_result_shape/{id}: + get: + summary: get the outline of a completed job's result + description: | + The JSON length and keys of a completed job's result, or of the value at `json_path` + in it, and the same for each of the first 100 elements of a list. Lets a viewer offer + the parts of a result too large to send inline without reading all of it. + operationId: getCompletedJobResultShape + tags: + - job + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - $ref: "#/components/parameters/JobId" + - name: json_path + description: dot-separated path into the result, as for getCompletedJobResult + in: query + schema: + type: string + responses: + "200": + description: result outline + content: + application/json: + schema: + type: object + properties: + type: + type: string + description: the JSON type of the value (object, array, string, ...) + length: + type: integer + description: characters in the value's JSON text + keys: + type: array + description: up to 20 of the keys, for an object + items: + type: string + item_count: + type: integer + description: the number of elements, for a list + items: + type: array + description: the first 100 elements, for a list + items: + type: object + properties: + length: + type: integer + keys: + type: array + items: + type: string + required: + - length + required: + - type + - length + /w/{workspace}/jobs_u/completed/get_result_maybe/{id}: get: summary: get completed job result if job is completed @@ -20297,6 +21110,9 @@ paths: flow_summary: type: string description: summary of the flow or workflow the approval belongs to + required_events: + type: integer + description: approvals the step requires; absent for a workflow as code approvers: type: array items: @@ -20309,6 +21125,11 @@ paths: type: integer approver: type: string + approved_at: + type: string + format: date-time + approved: + type: boolean view_token: type: string description: >- @@ -20563,6 +21384,11 @@ paths: type: integer approver: type: string + approved_at: + type: string + format: date-time + approved: + type: boolean required: - resume_id - approver @@ -22054,6 +22880,47 @@ paths: items: $ref: "#/components/schemas/WorkspaceIntegrations" + /w/{workspace}/native_triggers/integrations/workspace_apps: + get: + summary: list the services this workspace has its own OAuth app for + operationId: listNativeTriggerWorkspaceApps + tags: + - workspace_integration + parameters: + - $ref: "#/components/parameters/WorkspaceId" + responses: + "200": + description: services with a workspace OAuth app + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/NativeServiceName" + + /w/{workspace}/native_triggers/integrations/{service_name}/required_scopes: + get: + summary: list the scopes the service's triggers need + operationId: getNativeTriggerRequiredScopes + tags: + - workspace_integration + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: service_name + in: path + required: true + schema: + $ref: "#/components/schemas/NativeServiceName" + responses: + "200": + description: scopes a connection made for the service's triggers requests + content: + application/json: + schema: + type: array + items: + type: string + /w/{workspace}/native_triggers/integrations/{service_name}/exists: get: summary: check if integrations for a particular service exists @@ -22105,7 +22972,7 @@ paths: /w/{workspace}/native_triggers/integrations/{service_name}/generate_connect_url: post: - summary: generate connect url for native trigger service + summary: generate the authorize url of a connect made with the workspace OAuth app operationId: generateNativeTriggerServiceConnectUrl tags: - workspace_integration @@ -22118,17 +22985,18 @@ paths: $ref: "#/components/schemas/NativeServiceName" requestBody: description: >- - Where to save the connection (defaults to u/{caller}/native_{resource_type}). Uses - the workspace OAuth client, or the instance one when the instance shares it, and the - redirect URI registered on that client. + The scopes to request. Uses the workspace's own OAuth app and the redirect URI + registered on it; refused when the workspace has none. required: true content: application/json: schema: type: object properties: - resource_path: - type: string + scopes: + type: array + items: + type: string responses: "200": description: native trigger service connect url @@ -22262,7 +23130,7 @@ paths: /w/{workspace}/native_triggers/integrations/{service_name}/callback: post: - summary: native trigger service oauth callback + summary: exchange the code of a connect made with the workspace OAuth app operationId: nativeTriggerServiceCallback tags: - workspace_integration @@ -22290,11 +23158,11 @@ paths: - state responses: "200": - description: path of the saved connection + description: the token, to save like any connected resource content: application/json: schema: - type: string + $ref: "#/components/schemas/TokenResponse" /w/{workspace}/native_triggers/{service_name}/create: post: @@ -27816,6 +28684,38 @@ paths: application/json: schema: type: string + /concurrency_groups/{id}/key_status: + get: + summary: Get a job's concurrency key and whether its limit held it back + description: Requires read access to the job, the same as reading the run itself. Returns null when the job has no concurrency key. + operationId: getConcurrencyKeyStatus + tags: + - concurrencyGroups + parameters: + - $ref: "#/components/parameters/JobId" + responses: + "200": + description: concurrency key and deferral of the given job + content: + application/json: + schema: + type: object + nullable: true + properties: + key: + type: string + deferred_from: + type: string + format: date-time + nullable: true + description: When the job was first due. Set the first time its concurrency limit held it back, and kept after it ran. + released_at: + type: string + format: date-time + nullable: true + description: When the concurrency limit let in a job it had held back, as the time the job was last due. The rest until it started is queue time. + required: + - key /w/{workspace}/concurrency_groups/list_jobs: get: summary: Get intervals of job runtime concurrency @@ -28989,6 +29889,47 @@ paths: items: $ref: "#/components/schemas/EndpointTool" + /mcp/gateway/oauth/server/client/{client_id}: + get: + summary: get an MCP client registered with Windmill's OAuth server + description: | + The name and redirect URIs a client registered itself with, for the consent page to + show from the server rather than from the authorization URL. + operationId: getMcpOAuthServerClient + tags: + - mcp_oauth + parameters: + - name: client_id + in: path + required: true + schema: + type: string + responses: + "200": + description: the registered client + content: + application/json: + schema: + type: object + required: + - client_id + - client_name + - redirect_uris + - created_at + properties: + client_id: + type: string + client_name: + type: string + description: The name the client chose when it registered, unverified. + redirect_uris: + type: array + items: + type: string + created_at: + type: string + format: date-time + /mcp/oauth/discover: post: summary: discover MCP server OAuth metadata @@ -29718,6 +30659,15 @@ components: required: true schema: type: string + DangerouslyRevealSecrets: + name: dangerously_reveal_secrets + description: > + Return stored secrets in clear. Without it, every secret is replaced by a + placeholder, which a write sending it back unchanged keeps as the stored value. + in: query + required: false + schema: + type: boolean WorkspaceId: name: workspace in: path @@ -29746,9 +30696,10 @@ components: name: filters description: > JSON object, column name to filter. A number column takes an optional comparison - operator and a number (`>=10`), a boolean column a boolean, and any other column a - case-insensitive substring, or `=value` for an exact match. A `search_term` without - a `search_col` matches any column, case-insensitively. + operator and a number (`>=10`), a boolean column `true` or `false` (a boolean or that + string), and any other column a case-insensitive substring, or `=value` for an exact + match. Any other value on a boolean column, or an unknown column, is a 400. A + `search_term` without a `search_col` matches any column, case-insensitively. in: query schema: type: string @@ -33579,6 +34530,12 @@ components: type: string password: type: string + totp_code: + type: string + description: > + Current code of the account's authenticator app, or one of its recovery codes. Required once the account has + two-factor authentication enabled; the login answers "Two-factor code required" + when it is missing and the password is correct. required: - email - password @@ -33709,9 +34666,34 @@ components: items: type: string description: "List of path conflicts that block the offboarding. Empty on success." + conflict_items: + type: array + items: + $ref: "#/components/schemas/OffboardPathConflict" + description: "The same conflicts as `conflicts`, structured. Empty on success." summary: $ref: "#/components/schemas/OffboardSummary" + OffboardPathConflict: + type: object + properties: + workspace_id: + type: string + kind: + type: string + description: "Item kind, as its table name (script, flow, app, resource, variable, schedule, eval_dataset, http_trigger, ...)" + source_path: + type: string + description: "The offboarded user's item, under u/{username}/" + target_path: + type: string + description: "The existing item at the reassignment target" + required: + - workspace_id + - kind + - source_path + - target_path + OffboardSummary: type: object properties: @@ -33816,11 +34798,97 @@ components: type: string read_only: type: boolean + allowed_ips: + type: array + description: IPs or CIDRs the token may be used from; absent when it may be used from anywhere. + items: + type: string + admin: + type: boolean + description: | + The token carries workspace admin rights: it was minted with them and its owner is an + admin of the workspace it is bound to (any workspace when unbound). Set by /users/tokens/list. + super_admin: + type: boolean + description: | + The token carries superadmin rights: it was minted with them (a session always is) and + its owner is a superadmin. Set by /users/tokens/list. + risks: + type: array + description: what a token review flags on this token; empty for a token the server manages on its own + items: + $ref: "#/components/schemas/TokenRisk" required: - token_prefix - created_at - last_used_at - read_only + - risks + + TokenRisk: + type: string + description: > + superadmin / admin: minted with those rights (and the owner still an admin where the token + reaches), not narrowed by scopes or read-only mode. all_workspaces: not bound to a workspace. + never_expires: no expiration. unused: not used in over 90 days. + enum: [superadmin, admin, all_workspaces, never_expires, unused] + + TokenRiskCounts: + type: object + properties: + superadmin: + type: integer + admin: + type: integer + all_workspaces: + type: integer + never_expires: + type: integer + unused: + type: integer + required: + - superadmin + - admin + - all_workspaces + - never_expires + - unused + + TokenForReview: + type: object + properties: + email: + type: string + label: + type: string + expiration: + type: string + format: date-time + token_prefix: + type: string + created_at: + type: string + format: date-time + last_used_at: + type: string + format: date-time + scopes: + type: array + items: + type: string + workspace_id: + type: string + read_only: + type: boolean + risks: + type: array + items: + $ref: "#/components/schemas/TokenRisk" + required: + - token_prefix + - created_at + - last_used_at + - read_only + - risks ExternalJwtToken: type: object @@ -33940,6 +35008,9 @@ components: type: string workspace_id: type: string + description: | + Bind the token to this workspace: it is then refused on every other workspace and + on instance-level endpoints. Omit for a token that reaches every workspace. read_only: type: boolean description: | @@ -33949,9 +35020,24 @@ components: super_admin: type: boolean description: | - For an MCP token (an `mcp:` scope) owned by a superadmin: carry the owner's - superadmin rights, reaching every workspace rather than only their - memberships. Ignored for other tokens, which always carry them. + Carry the owner's superadmin rights: admin in every workspace, including ones + they are not a member of, and the superadmin endpoints. Defaults to false, and + is ignored when the owner or the calling token does not hold them. + admin: + type: boolean + description: | + Carry the owner's workspace admin rights in the workspaces the token reaches. + Defaults to false: the token then acts as a regular member. Ignored when the + calling token does not hold them. + allowed_ips: + type: array + description: | + IPs or CIDRs (IPv4 or IPv6) the token may be used from; omit to allow any. + A request from elsewhere is refused as unauthenticated. A token that is itself + restricted can only create tokens within its own networks, and creates one + restricted to them when this is omitted. + items: + type: string NewTokenImpersonate: type: object @@ -33965,6 +35051,18 @@ components: type: string workspace_id: type: string + description: Bind the token to this workspace; omit for a token that reaches every workspace. + super_admin: + type: boolean + description: Carry the impersonated account's superadmin rights. Defaults to false. + admin: + type: boolean + description: Carry the impersonated account's workspace admin rights. Defaults to false. + allowed_ips: + type: array + description: IPs or CIDRs the token may be used from; omit to allow any. + items: + type: string required: - impersonate_email @@ -34134,6 +35232,9 @@ components: it unchanged; send null to clear it. Changing it re-arms the workspace's variable expiration handler. format: date-time + unlink_account: + type: boolean + description: Detach the OAuth account the variable refreshes through, deleting it when no other variable uses it. labels: type: array items: @@ -34141,6 +35242,124 @@ components: ws_specific: type: boolean + ClientIpTrustView: + type: object + properties: + networks: + type: array + items: + type: string + hosts: + type: array + items: + type: object + properties: + name: + type: string + addresses: + type: array + items: + type: string + required: + - name + - addresses + cloudflare: + type: boolean + required: + - networks + - hosts + - cloudflare + + ClientIpDiagnostics: + type: object + properties: + peer: + type: string + nullable: true + forwarding_header: + type: string + nullable: true + client_ip: + type: string + nullable: true + description: as audit entries and the login rate limit record it + enforced_client_ip: + type: string + nullable: true + description: as token IP allowlists see it + trusted_proxies_set: + type: boolean + private_ranges_trusted: + type: boolean + description: a whole private range is trusted, so any host on the private network can name its own client address + client_ip_header: + type: string + nullable: true + enforced: + $ref: "#/components/schemas/ClientIpTrustView" + attributed: + description: absent when it is the enforced view, which it differs from only by Cloudflare + allOf: + - $ref: "#/components/schemas/ClientIpTrustView" + nullable: true + configuration: + description: what the trust is built from; a value whose environment variable is set cannot be changed from the settings + type: object + properties: + trusted_proxies: + type: object + properties: + value: + type: string + nullable: true + from_env: + type: boolean + required: [from_env] + trust_cloudflare: + type: object + properties: + value: + type: boolean + from_env: + type: boolean + required: [value, from_env] + client_ip_header: + type: object + properties: + value: + type: string + nullable: true + from_env: + type: boolean + required: [from_env] + required: [trusted_proxies, trust_cloudflare, client_ip_header] + forwarders: + type: array + items: + type: object + properties: + peer: + type: string + attributed_only: + type: boolean + description: a Cloudflare edge, believed by audit entries and the login rate limit, never by token IP allowlists + last_seen: + type: string + format: date-time + requests: + type: integer + required: + - peer + - attributed_only + - last_seen + - requests + required: + - trusted_proxies_set + - private_ranges_trusted + - configuration + - enforced + - forwarders + AuditLog: type: object properties: @@ -34256,6 +35475,18 @@ components: type: object span: type: string + client_ip: + type: string + description: Address of the client that made the request. Forwarding headers are believed only from the proxies listed in the TRUSTED_PROXIES environment variable, or, when it is unset, from loopback and the private ranges, where a reverse proxy usually sits. Any host that reaches the server directly from a private address can then name any address here; peer_ip and forwarded_for tell such an entry apart. Absent on entries no request stands behind. + user_agent: + type: string + description: User-Agent header of the request. + peer_ip: + type: string + description: Address the connection itself came from, when it is not client_ip (the proxy that forwarded the request). + forwarded_for: + type: string + description: The forwarding header as the request carried it (CLIENT_IP_HEADER when set, else X-Forwarded-For), whether or not its sender was trusted. required: - workspace_id - id @@ -34443,9 +35674,11 @@ components: - has_preprocessor RecentRunStatus: - description: a failure someone or something marked as handled is `resolved`, not `failure` + description: > + a failure someone or something marked as handled is `resolved`, not `failure`; a run + waiting for an approval is `suspended`, not `running` type: string - enum: [success, failure, resolved, canceled, running] + enum: [success, failure, resolved, canceled, running, suspended] RecentRunHiddenItem: type: object @@ -34763,6 +35996,12 @@ components: items: type: string description: OAuth scopes the linked account was connected with + client: + type: string + description: OAuth client the linked account refreshes through + is_workspace_integration: + type: boolean + description: The linked account was connected through the workspace's own OAuth app created_by: type: string edited_at: @@ -39194,8 +40433,9 @@ components: description: > Publisher opt-in to app sandbox isolation (alpha). When true the app is isolated from each viewer's Windmill session. When false/absent - the app runs same-origin with the viewer's full session (the - default, pre-isolation behavior). + the app runs same-origin with the session of viewers who are members + of the app's workspace; anonymous viewers and everyone else always + get the isolated render. frontend_sdk_scopes: type: array items: @@ -39311,6 +40551,179 @@ components: - label - requires_resource_path + TokenAdminReliance: + type: object + properties: + workspace_id: + type: string + username: + description: the caller's username in the workspace + type: string + folders: + description: folders within the scopes the caller cannot read, or write to when `folders_write` (first 50) + type: array + items: + type: string + folders_total: + type: integer + folders_write: + description: | + the folders are ones the caller cannot write to (the token can change items), + rather than ones they cannot read + type: boolean + other_users_items: + description: items under other users' paths not shared with the caller + type: integer + assets: + description: resources the runnables named by the scopes reference + type: array + items: + type: object + properties: + runnable_kind: + type: string + runnable_path: + type: string + kind: + type: string + path: + type: string + required: + - runnable_kind + - runnable_path + - kind + - path + admin_only: + description: admin-only actions the scopes allow + type: array + items: + type: string + required: + - workspace_id + - username + - folders + - folders_total + - folders_write + - other_users_items + - assets + - admin_only + + TokenIntrospection: + type: object + properties: + kind: + type: string + enum: [session, api_token, jwt, external, superadmin_secret] + email: + type: string + username: + type: string + label: + type: string + token_prefix: + type: string + created_at: + type: string + format: date-time + expiration: + type: string + format: date-time + workspace_id: + description: the one workspace the token is bound to; absent when it is not bound + type: string + workspace_ids: + description: the workspaces a signed token is bound to, when it names several + type: array + items: + type: string + scopes: + description: absent when the token is unrestricted + type: array + items: + type: string + read_only: + type: boolean + admin_withheld: + description: | + the token does not carry its owner's workspace admin rights; the rights it does hold + in a workspace are in `workspace` + type: boolean + super_admin: + description: | + whether the token reaches superadmin routes: its owner is a superadmin, and it is + neither a job token nor one that withholds those rights + type: boolean + allowed_ips: + type: array + items: + type: string + job_id: + type: string + format: uuid + workspace: + $ref: "#/components/schemas/TokenWorkspaceAccess" + route: + $ref: "#/components/schemas/TokenRouteCheck" + required: + - kind + - email + - username + - read_only + - admin_withheld + - super_admin + + TokenWorkspaceAccess: + type: object + properties: + workspace_id: + type: string + usable: + description: whether the token is accepted in this workspace at all + type: boolean + is_admin: + type: boolean + is_operator: + type: boolean + groups: + type: array + items: + type: string + folders: + type: array + items: + type: object + properties: + name: + type: string + write: + type: boolean + owner: + type: boolean + required: + - name + - write + - owner + required: + - workspace_id + - usable + + TokenRouteCheck: + type: object + properties: + method: + type: string + path: + type: string + allowed: + type: boolean + reason: + description: why the route layer refuses the token, when it does + type: string + required: + - method + - path + - allowed + ScopeDomain: type: object properties: @@ -39480,7 +40893,7 @@ components: a different credential from the low-code embed token. sandbox: type: boolean - description: Publisher opted this app into sandbox isolation. When false the viewer runs the app same-origin with its full session. + description: Whether the viewer must render the app isolated, because the publisher opted in or because the viewer is not a member of the app's workspace. When false the viewer runs the app same-origin with its full session. app_path: type: string nullable: true @@ -41465,6 +42878,7 @@ components: - RestrictPublicRunSharing - RestrictGuestAppDeployment - RequireIsolatedForks + - RequireSso RuleBypasserGroups: type: array description: Groups that can bypass this ruleset @@ -41796,12 +43210,6 @@ components: workspace: type: boolean description: Whether this is the workspace connection, which every member may use - managed: - type: boolean - description: >- - Whether the integration trigger connect flow made it. Any other connection is a - resource connected from Resources, which triggers can use but only Resources can - replace or delete. scopes: type: array nullable: true @@ -41817,7 +43225,6 @@ components: required: - path - workspace - - managed CreateTriggerResponse: type: object diff --git a/backend/windmill-api/src/admin_reliance.rs b/backend/windmill-api/src/admin_reliance.rs new file mode 100644 index 0000000000..fbd36f6d9d --- /dev/null +++ b/backend/windmill-api/src/admin_reliance.rs @@ -0,0 +1,693 @@ +//! What a token made without its owner's workspace admin rights cannot reach, that the owner +//! reaches only because they are admin. Read by the token forms before minting, and appended +//! to the refusals such a token meets. + +use std::sync::Arc; + +use axum::{extract::Request, middleware::Next, response::Response, Extension, Json}; +use http::StatusCode; +use serde::{Deserialize, Serialize}; +use windmill_api_auth::{ + auth::maybe_get_workspace_id_from_path, ApiAuthed, AuthCache, OptJobAuthed, +}; +use windmill_common::{ + auth::{get_folders_for_user, get_groups_for_user}, + client_ip::client_ip_of, + error::{Error, JsonResult, Result, ServerError}, + scopes::ScopeDefinition, + DB, +}; + +use crate::token::ALL_SCOPES; + +const MAX_FOLDERS: usize = 50; +const MAX_ASSETS: usize = 20; +const MAX_WORKSPACES: i64 = 50; + +/// MCP scopes that serve the session toolset, which acts on the whole workspace. The others +/// name runnables (`scripts`, `flows`, `favorites`), endpoints, hub scripts or workspaces. +const MCP_SESSION_ACCESS: &[&str] = &["all", "session", "read_only", "read_run"]; + +/// Workspace actions only an admin can take, by the scope that would let a token attempt them. +const ADMIN_ONLY: &[(&str, &str)] = &[ + ("workspaces:write", "change workspace settings"), + ( + "users:write", + "add, remove or change the role of workspace members", + ), + ("groups:write", "edit groups you do not own"), + ("folders:write", "edit folders you do not own"), +]; + +#[derive(Deserialize)] +pub(crate) struct AdminRelianceRequest { + /// The workspaces the token will reach; omitted, every workspace the caller administers. + workspace_ids: Option>, + /// The token's scopes; omitted, an unscoped token. + scopes: Option>, + #[serde(default)] + read_only: bool, +} + +#[derive(Serialize, Debug, PartialEq)] +pub(crate) struct AssetOutOfReach { + runnable_kind: String, + runnable_path: String, + kind: String, + path: String, +} + +#[derive(Serialize, Debug)] +pub(crate) struct WorkspaceAdminReliance { + workspace_id: String, + /// The caller's username there, which a folder grant names. + username: String, + /// Folders within the scopes the caller cannot read (or write, see `folders_write`), first + /// `MAX_FOLDERS` by name. + folders: Vec, + folders_total: usize, + /// The folders are ones the caller cannot write to, rather than cannot read: the token can + /// change items. + folders_write: bool, + /// Scripts, flows, apps, resources and variables under other users' `u/` paths, not shared + /// with the caller, within the scopes. + other_users_items: i64, + /// Resources that the runnables the scopes name reference in their code. The asset parsers + /// record no variables, so none are reported. + assets: Vec, + admin_only: Vec, +} + +impl WorkspaceAdminReliance { + fn is_empty(&self) -> bool { + self.folders_total == 0 + && self.other_users_items == 0 + && self.assets.is_empty() + && self.admin_only.is_empty() + } +} + +/// Which item paths a set of scopes reaches. +#[derive(Debug, PartialEq)] +enum PathReach { + All, + Patterns(Vec), +} + +impl PathReach { + fn of(scopes: Option<&[String]>) -> Option { + let Some(scopes) = scopes else { + return Some(Self::All); + }; + let mut patterns = vec![]; + for scope in scopes { + match scope_paths(scope) { + Some(None) => return Some(Self::All), + Some(Some(p)) => patterns.extend(p), + None => {} + } + } + (!patterns.is_empty()).then_some(Self::Patterns(patterns)) + } + + /// Whether some path under `prefix` (ending with `/`) is reached. + fn covers_prefix(&self, prefix: &str) -> bool { + match self { + Self::All => true, + Self::Patterns(patterns) => patterns.iter().any(|p| match p.strip_suffix('*') { + Some(head) => prefix.starts_with(head) || head.starts_with(prefix), + None => p.starts_with(prefix), + }), + } + } + + fn covers_other_users(&self, username: &str) -> bool { + let own = format!("u/{username}/"); + match self { + Self::All => true, + Self::Patterns(patterns) => patterns.iter().any(|p| { + (p == "*" || p.starts_with("u/") || "u/".starts_with(p.trim_end_matches('*'))) + && !p.starts_with(&own) + }), + } + } +} + +/// The item paths one scope reaches: `None` for a scope naming no items, `Some(None)` for +/// every path, else its path patterns. +fn scope_paths(scope: &str) -> Option>> { + if scope == "*" { + return Some(None); + } + let parts: Vec<&str> = scope.split(':').collect(); + let domain = parts[0]; + let resource_from = match domain { + // The session toolsets act on the whole workspace. + "mcp" => match parts.get(1).copied() { + Some("scripts" | "flows") => 2, + Some(access) if MCP_SESSION_ACCESS.contains(&access) => return Some(None), + _ => return None, + }, + "jobs" if parts.get(1) == Some(&"run") => 3, + _ => { + let path_scoped = ALL_SCOPES + .iter() + .flat_map(|d| d.scopes.iter()) + .any(|s| s.requires_resource_path && s.value.split(':').next() == Some(domain)); + if !path_scoped { + return None; + } + 2 + } + }; + let resource = parts + .get(resource_from..) + .map(|p| p.join(":")) + .unwrap_or_default(); + if resource.is_empty() { + return Some(None); + } + Some(Some(resource.split(',').map(str::to_string).collect())) +} + +/// The runnables a scope names by path, as `(usage_kind, pattern)`. +fn scope_runnables(scope: &str) -> Vec<(&'static str, String)> { + let parts: Vec<&str> = scope.split(':').collect(); + let (kind, from) = match parts.as_slice() { + ["mcp", "scripts", ..] => ("script", 2), + ["mcp", "flows", ..] => ("flow", 2), + ["jobs", "run", "scripts", ..] => ("script", 3), + ["jobs", "run", "flows", ..] => ("flow", 3), + _ => return vec![], + }; + let resource = parts.get(from..).map(|p| p.join(":")).unwrap_or_default(); + resource + .split(',') + .filter(|p| !p.is_empty() && *p != "*") + .map(|p| (kind, p.to_string())) + .collect() +} + +/// Whether the scopes reach the item of `domain` (`scripts`, `flows`, `apps`, `resources` or +/// `variables`) at `path`. +fn reaches_item(scopes: Option<&[String]>, domain: &str, path: &str) -> bool { + let Some(scopes) = scopes else { + return true; + }; + scopes.iter().any(|scope| { + let parts: Vec<&str> = scope.split(':').collect(); + // The domain the scope names items of, and where its path patterns start. + let (scope_domain, from) = match parts.as_slice() { + ["*"] => return true, + ["mcp", kind @ ("scripts" | "flows"), ..] => (*kind, 2), + ["mcp", access, ..] => return MCP_SESSION_ACCESS.contains(access), + ["jobs", "run", kind @ ("scripts" | "flows"), ..] => (*kind, 3), + [d, _, ..] => (*d, 2), + _ => return false, + }; + if scope_domain != domain { + return false; + } + let resource = parts.get(from..).map(|p| p.join(":")).unwrap_or_default(); + resource.is_empty() || resource.split(',').any(|p| pattern_matches(p, path)) + }) +} + +fn pattern_matches(pattern: &str, path: &str) -> bool { + match pattern.strip_suffix('*') { + Some(head) => path.starts_with(head), + None => pattern == path, + } +} + +/// The item paths the token can change, so a folder there it can only read still costs it +/// access. `None` when it changes no item. +fn write_reach(scopes: Option<&[String]>, read_only: bool) -> Option { + if read_only { + return None; + } + let Some(scopes) = scopes else { + return Some(PathReach::All); + }; + // `mcp:all` with `mcp:read_only` or `mcp:read_run` is the Read levels of the toolset. + let mcp_narrowed = scopes + .iter() + .any(|s| s == "mcp:read_only" || s == "mcp:read_run"); + let writing: Vec = scopes + .iter() + .filter(|s| { + let mut parts = s.split(':'); + match (parts.next(), parts.next()) { + (Some("*"), _) => true, + (Some("mcp"), Some(access)) => matches!(access, "all" | "session") && !mcp_narrowed, + (_, Some(action)) => action == "write", + _ => false, + } + }) + .cloned() + .collect(); + PathReach::of(Some(&writing)) +} + +fn admin_only_actions(scopes: Option<&[String]>, read_only: bool) -> Vec { + if read_only { + return vec![]; + } + let grants: Option> = scopes.map(|s| { + s.iter() + .filter_map(|s| ScopeDefinition::from_scope_string(s).ok()) + .collect() + }); + let unscoped = scopes.is_none_or(|s| s.iter().any(|s| s == "*")); + ADMIN_ONLY + .iter() + .filter(|(required, _)| { + unscoped + || ScopeDefinition::from_required_scope_string(required).is_ok_and(|required| { + grants.iter().flatten().any(|grant| grant.grants(&required)) + }) + }) + .map(|(_, what)| what.to_string()) + .collect() +} + +/// `mcp:favorites` stands for the caller's favorite scripts and flows in that workspace. +async fn expand_favorites( + db: &DB, + w_id: &str, + username: &str, + scopes: Option<&[String]>, +) -> Result>> { + let Some(scopes) = scopes else { + return Ok(None); + }; + let mut out: Vec = scopes + .iter() + .filter(|s| *s != "mcp:favorites") + .cloned() + .collect(); + if out.len() < scopes.len() { + let favorites = sqlx::query!( + r#"SELECT favorite_kind::text AS "kind!", path FROM favorite + WHERE usr = $1 AND workspace_id = $2 AND favorite_kind IN ('script', 'flow')"#, + username, + w_id + ) + .fetch_all(db) + .await?; + out.extend( + favorites + .into_iter() + .map(|f| format!("mcp:{}s:{}", f.kind, f.path)), + ); + } + Ok(Some(out)) +} + +async fn workspace_reliance( + db: &DB, + w_id: &str, + username: &str, + email: &str, + req: &AdminRelianceRequest, +) -> Result { + let expanded = expand_favorites(db, w_id, username, req.scopes.as_deref()).await?; + let scopes = expanded.as_deref(); + let reach = PathReach::of(scopes); + let groups = get_groups_for_user(w_id, username, email, db).await?; + let memberships = get_folders_for_user(w_id, username, &groups, db).await?; + let member_folders: Vec = memberships + .iter() + .map(|(name, _, _)| name.clone()) + .collect(); + let writable_folders: Vec<&str> = memberships + .iter() + .filter(|(_, write, owner)| *write || *owner) + .map(|(name, _, _)| name.as_str()) + .collect(); + let writes = write_reach(scopes, req.read_only); + let mut perms: Vec = groups.iter().map(|g| format!("g/{g}")).collect(); + perms.push(format!("u/{username}")); + + // Each listed folder, and whether the token can change items there (so reading is not enough). + let mut listed: Vec<(String, bool)> = vec![]; + if let Some(reach) = &reach { + for f in sqlx::query_scalar!( + "SELECT name FROM folder WHERE workspace_id = $1 ORDER BY name", + w_id + ) + .fetch_all(db) + .await? + { + let prefix = format!("f/{f}/"); + if !reach.covers_prefix(&prefix) { + continue; + } + let needs_write = writes.as_ref().is_some_and(|w| w.covers_prefix(&prefix)); + let short = if needs_write { + !writable_folders.contains(&f.as_str()) + } else { + !member_folders.contains(&f) + }; + if short { + listed.push((f, needs_write)); + } + } + } + let folders_write = listed.iter().any(|(_, w)| *w); + let mut folders: Vec = listed.into_iter().map(|(f, _)| f).collect(); + let folders_total = folders.len(); + folders.truncate(MAX_FOLDERS); + + let other_users_items = if reach + .as_ref() + .is_some_and(|r| r.covers_other_users(username)) + { + let own = format!("u/{username}/"); + sqlx::query!( + r#"SELECT 'scripts' AS "domain!", path AS "path!" FROM script WHERE workspace_id = $1 AND NOT archived + AND starts_with(path, 'u/') AND NOT starts_with(path, $2) AND NOT extra_perms ?| $3 + UNION + SELECT 'flows', path FROM flow WHERE workspace_id = $1 AND NOT archived + AND starts_with(path, 'u/') AND NOT starts_with(path, $2) AND NOT extra_perms ?| $3 + UNION ALL + SELECT 'apps', path FROM app WHERE workspace_id = $1 + AND starts_with(path, 'u/') AND NOT starts_with(path, $2) AND NOT extra_perms ?| $3 + UNION ALL + SELECT 'resources', path FROM resource WHERE workspace_id = $1 + AND starts_with(path, 'u/') AND NOT starts_with(path, $2) AND NOT extra_perms ?| $3 + UNION ALL + SELECT 'variables', path FROM variable WHERE workspace_id = $1 + AND starts_with(path, 'u/') AND NOT starts_with(path, $2) AND NOT extra_perms ?| $3 + LIMIT 10000"#, + w_id, + own, + &perms[..], + ) + .fetch_all(db) + .await? + .into_iter() + .filter(|item| reaches_item(scopes, &item.domain, &item.path)) + .count() as i64 + } else { + 0 + }; + + let runnables: Vec<(&str, String)> = scopes + .iter() + .flat_map(|s| s.iter()) + .flat_map(|s| scope_runnables(s)) + .collect(); + let mut assets = vec![]; + if !runnables.is_empty() { + let own = format!("u/{username}/"); + let candidates: Vec = sqlx::query!( + r#"SELECT DISTINCT usage_kind::text AS "usage_kind!", usage_path, kind::text AS "kind!", path + FROM asset + WHERE workspace_id = $1 AND usage_kind IN ('script', 'flow') + AND kind = 'resource' + ORDER BY usage_path, path"#, + w_id + ) + .fetch_all(db) + .await? + .into_iter() + .filter(|a| { + runnables + .iter() + .any(|(kind, p)| *kind == a.usage_kind && pattern_matches(p, &a.usage_path)) + }) + .filter(|a| { + // A member reads their own space, folders they are in and their groups' `g/` paths. + let mut segments = a.path.splitn(3, '/'); + let (space, name) = (segments.next(), segments.next().unwrap_or_default()); + !a.path.starts_with(&own) + && !(space == Some("f") && member_folders.iter().any(|m| m == name)) + && !(space == Some("g") && groups.iter().any(|g| g == name)) + }) + .map(|a| AssetOutOfReach { + runnable_kind: a.usage_kind, + runnable_path: a.usage_path, + kind: a.kind, + path: a.path, + }) + .collect(); + if !candidates.is_empty() { + let paths: Vec = candidates.iter().map(|a| a.path.clone()).collect(); + let shared = sqlx::query_scalar!( + "SELECT path FROM resource + WHERE workspace_id = $1 AND path = ANY($2) AND extra_perms ?| $3", + w_id, + &paths[..], + &perms[..], + ) + .fetch_all(db) + .await?; + assets = candidates + .into_iter() + .filter(|a| !shared.contains(&a.path)) + .take(MAX_ASSETS) + .collect(); + } + } + + Ok(WorkspaceAdminReliance { + workspace_id: w_id.to_string(), + username: username.to_string(), + folders, + folders_total, + folders_write, + other_users_items, + assets, + admin_only: admin_only_actions(scopes, req.read_only), + }) +} + +/// For each workspace the caller administers among those asked, what a token with these +/// scopes would lose without their admin rights. Only a credential carrying those rights may +/// ask, since the answer names folders a member cannot see. +pub(crate) async fn admin_reliance( + authed: ApiAuthed, + Extension(db): Extension, + Json(req): Json, +) -> JsonResult> { + if authed.admin_withheld || authed.job_id.is_some() || authed.scopes.is_some() { + return Err(Error::PermissionDenied( + "Checking what a token would need admin rights for takes a credential carrying your admin rights" + .to_string(), + )); + } + let memberships = sqlx::query!( + "SELECT workspace_id, username FROM usr + WHERE email = $1 AND is_admin AND NOT disabled + AND ($2::text[] IS NULL OR workspace_id = ANY($2)) + ORDER BY workspace_id LIMIT $3", + authed.email, + req.workspace_ids.as_deref(), + MAX_WORKSPACES, + ) + .fetch_all(&db) + .await?; + let mut out = vec![]; + for m in memberships { + let reliance = + workspace_reliance(&db, &m.workspace_id, &m.username, &authed.email, &req).await?; + if !reliance.is_empty() { + out.push(reliance); + } + } + Ok(Json(out)) +} + +const WITHHELD_ADMIN_HINT: &str = "This credential does not carry your workspace admin rights: \ +it is a token created without them, or a job such a token started, so it acts as a regular \ +member here. If it needs access your admin role gave you, add yourself to the folder holding the \ +item (as a writer to change it), or create a token with Workspace admin rights."; + +/// Refusal bodies a 400 can carry that a missing grant explains. +fn reads_as_refusal(body: &str) -> bool { + let body = body.to_ascii_lowercase(); + [ + "permission", + "not a writer", + "owner", + "not authorized", + "admin", + ] + .iter() + .any(|k| body.contains(k)) +} + +/// Appends [`WITHHELD_ADMIN_HINT`] to a workspace route's refusal (an [`Error`] response, never a +/// body a job chose) when the credential withholds admin rights its owner holds there. +/// Resolved only once a request has been refused, so requests that succeed pay nothing beyond +/// reading the header. +pub(crate) async fn hint_withheld_admin(req: Request, next: Next) -> Response { + let token = req + .headers() + .get(http::header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .map(str::to_string); + let path_vec: Vec<&str> = req.uri().path().split('/').collect(); + let w_id = maybe_get_workspace_id_from_path(&path_vec); + let (Some(token), Some(w_id)) = (token, w_id) else { + return next.run(req).await; + }; + let cache = req.extensions().get::>().cloned(); + let db = req.extensions().get::().cloned(); + let client_ip = client_ip_of(req.extensions(), req.headers()); + + let res = next.run(req).await; + let status = res.status(); + if !matches!( + status, + StatusCode::BAD_REQUEST + | StatusCode::UNAUTHORIZED + | StatusCode::FORBIDDEN + | StatusCode::NOT_FOUND + ) || res.extensions().get::().is_none() + { + return res; + } + let (Some(cache), Some(db)) = (cache, db) else { + return res; + }; + let Some(OptJobAuthed { authed, .. }) = cache + .get_opt_job_authed(Some(w_id.clone()), &token, client_ip) + .await + else { + return res; + }; + if !authed.admin_withheld || authed.is_admin { + return res; + } + let owner_is_admin = sqlx::query_scalar!( + "SELECT is_admin FROM usr WHERE workspace_id = $1 AND email = $2 AND NOT disabled", + w_id, + authed.email + ) + .fetch_optional(&db) + .await + .ok() + .flatten() + .unwrap_or(false); + if !owner_is_admin { + return res; + } + + const MAX_HINTED_BODY: u64 = 64 * 1024; + if axum::body::HttpBody::size_hint(res.body()) + .upper() + .is_none_or(|n| n > MAX_HINTED_BODY) + { + return res; + } + let (mut parts, body) = res.into_parts(); + let Ok(bytes) = axum::body::to_bytes(body, MAX_HINTED_BODY as usize).await else { + return Response::from_parts(parts, axum::body::Body::empty()); + }; + let text = String::from_utf8_lossy(&bytes); + if status == StatusCode::BAD_REQUEST && !reads_as_refusal(&text) { + return Response::from_parts(parts, axum::body::Body::from(bytes)); + } + parts.headers.remove(http::header::CONTENT_LENGTH); + Response::from_parts( + parts, + axum::body::Body::from(format!("{text}\n\n{WITHHELD_ADMIN_HINT}")), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn s(v: &[&str]) -> Vec { + v.iter().map(|x| x.to_string()).collect() + } + + #[test] + fn reach_follows_the_scopes() { + assert_eq!(PathReach::of(None), Some(PathReach::All)); + assert_eq!( + PathReach::of(Some(&s(&["users:read", "mcp:endpoints:listJobs"]))), + None + ); + assert_eq!( + PathReach::of(Some(&s(&["scripts:read"]))), + Some(PathReach::All) + ); + assert_eq!(PathReach::of(Some(&s(&["mcp:all"]))), Some(PathReach::All)); + assert_eq!(PathReach::of(Some(&s(&["mcp:workspaces:a,b"]))), None); + let r = + PathReach::of(Some(&s(&["scripts:read:f/etl/*", "jobs:run:flows:u/me/x"]))).unwrap(); + assert!(r.covers_prefix("f/etl/")); + assert!(!r.covers_prefix("f/billing/")); + assert!(!r.covers_other_users("me")); + let r = PathReach::of(Some(&s(&["resources:read:f/*"]))).unwrap(); + assert!(r.covers_prefix("f/billing/")); + assert!(!r.covers_other_users("me")); + let r = PathReach::of(Some(&s(&["variables:read:u/bob/*"]))).unwrap(); + assert!(r.covers_other_users("me")); + } + + #[test] + fn runnables_named_by_scopes() { + assert_eq!( + scope_runnables("mcp:scripts:f/etl/sync,f/etl/load"), + vec![ + ("script", "f/etl/sync".to_string()), + ("script", "f/etl/load".to_string()) + ] + ); + assert_eq!( + scope_runnables("jobs:run:flows:f/x/*"), + vec![("flow", "f/x/*".to_string())] + ); + assert!(scope_runnables("mcp:scripts:*").is_empty()); + assert!(scope_runnables("scripts:read:f/x/y").is_empty()); + } + + #[test] + fn admin_only_follows_the_scopes() { + assert_eq!(admin_only_actions(None, false).len(), ADMIN_ONLY.len()); + assert!(admin_only_actions(None, true).is_empty()); + assert!(admin_only_actions(Some(&s(&["scripts:write"])), false).is_empty()); + assert_eq!( + admin_only_actions(Some(&s(&["workspaces:write"])), false), + vec!["change workspace settings".to_string()] + ); + } + + #[test] + fn item_reach_follows_domain_and_path() { + let sc = s(&["scripts:read:u/alice/x", "mcp:flows:u/bob/*"]); + assert!(reaches_item(Some(&sc), "scripts", "u/alice/x")); + assert!(!reaches_item(Some(&sc), "scripts", "u/bob/y")); + assert!(!reaches_item(Some(&sc), "resources", "u/alice/x")); + assert!(reaches_item(Some(&sc), "flows", "u/bob/y")); + assert!(reaches_item( + Some(&s(&["variables:read"])), + "variables", + "u/bob/v" + )); + assert!(reaches_item(Some(&s(&["mcp:all"])), "apps", "u/bob/a")); + assert!(reaches_item(None, "apps", "u/bob/a")); + } + + #[test] + fn write_access_follows_the_scopes() { + let w = |sc: &[&str]| write_reach(Some(&s(sc)), false); + assert_eq!(write_reach(None, false), Some(PathReach::All)); + assert_eq!(write_reach(None, true), None); + assert_eq!(w(&["scripts:read", "jobs:run:scripts"]), None); + assert_eq!(w(&["mcp:all"]), Some(PathReach::All)); + assert_eq!(w(&["mcp:read_run"]), None); + assert_eq!(w(&["mcp:scripts:f/x/y"]), None); + assert_eq!(w(&["mcp:all", "mcp:read_only"]), None); + // Writing reaches only where a write scope does, not every folder the token reads. + let mixed = w(&["scripts:read:f/etl/*", "variables:write:u/admin/*"]).unwrap(); + assert!(!mixed.covers_prefix("f/etl/")); + assert!(w(&["scripts:write:f/x/*"]).unwrap().covers_prefix("f/x/")); + } +} diff --git a/backend/windmill-api/src/ai.rs b/backend/windmill-api/src/ai.rs index 996331cb9e..ca488af02e 100644 --- a/backend/windmill-api/src/ai.rs +++ b/backend/windmill-api/src/ai.rs @@ -439,6 +439,11 @@ async fn resolve_provider_credentials( } else { resource.platform }; + let mut custom_headers = HashMap::with_capacity(resource.headers.len()); + for (name, value) in resource.headers { + let value = resolve_var(value, db, w_id, user_db.as_ref(), authed).await?; + custom_headers.insert(name, value); + } Ok(ProviderCredentials { provider: provider.clone(), @@ -455,7 +460,7 @@ async fn resolve_provider_credentials( anthropic_federation: None, vertex_workload_identity, platform, - custom_headers: resource.headers, + custom_headers, }) } AIResource::AnthropicFederated(resource) => { @@ -934,7 +939,8 @@ impl ModelPolicy { .iter() .any(|p| path.ends_with(p)); if !generates { - if ["count_tokens", "input_tokens", "embeddings"] + // Decisions answer with short typed values and have no output-token field. + if ["count_tokens", "input_tokens", "embeddings", "decisions"] .iter() .any(|p| path.ends_with(p)) { @@ -2751,6 +2757,13 @@ mod tests { .unwrap(), raw ); + let raw = Bytes::from_static(br#"{"model":"gpt-4o","input":"x","questions":[]}"#); + assert_eq!( + policy + .limit_body("gpt-4o", &AIProvider::OpenAI, &Standard, "decisions", &raw) + .unwrap(), + raw + ); assert_eq!(policy.output_tokens("gpt-4o", Some(100000)), Some(4000)); assert_eq!(policy.output_tokens("gpt-4o", None), Some(4000)); assert_eq!(policy.output_tokens("unlimited", Some(9)), Some(9)); diff --git a/backend/windmill-api/src/ai_evals/run.rs b/backend/windmill-api/src/ai_evals/run.rs index 10266a82aa..860c899dbe 100644 --- a/backend/windmill-api/src/ai_evals/run.rs +++ b/backend/windmill-api/src/ai_evals/run.rs @@ -582,6 +582,28 @@ pub async fn run_experiment( ))); } + // Cases are written by anyone who can write the dataset, and the run resolves their values + // with the launcher's token. + for (index, case) in cases.iter().enumerate() { + let interpolates = + |json: &str| windmill_common::variables::untrusted_arg_interpolates(json); + if interpolates(&serde_json::to_string(&case.input)?) + || case + .expected + .as_ref() + .is_some_and(|e| interpolates(e.get())) + { + return Err(Error::BadRequest(format!( + "Case {} of eval dataset {} holds $var:, $jsonvar:, $res: or $encrypted: \ + references or a $WM_* variable name, which an eval run does not resolve. Put \ + the value itself in the case, or read the variable inside the script being \ + evaluated.", + index + 1, + payload.dataset + ))); + } + } + let case_count = cases.len(); // Resolved through the caller's own db, so a run executes only runnables the caller may read, // and what resolving pinned is baked into the flow. Recorded per cell at launch rather than diff --git a/backend/windmill-api/src/ai_session_tools/deploy.rs b/backend/windmill-api/src/ai_session_tools/deploy.rs index 4b9a185ece..0cab057627 100644 --- a/backend/windmill-api/src/ai_session_tools/deploy.rs +++ b/backend/windmill-api/src/ai_session_tools/deploy.rs @@ -1152,6 +1152,7 @@ const TRIGGER_RUNTIME_KEYS: &[&str] = &[ "last_server_ping", "extra_perms", "permissioned_as", + "preserve_permissioned_as", "subscription_id", "push_auth_config", ]; @@ -2155,20 +2156,39 @@ pub(super) async fn show_deploy_review(ctx: &Ctx<'_>, args: &Value) -> ToolResul .iter() .filter(|item| item.get("digest").is_some()) .count(); + // Windmill's own "Review & deploy drafts" page. + let review_url = ctx.page_url(&format!( + "/forks/compare?workspace_id={}&mode=draft", + enc(ctx.w_id) + )); + let item_lines: Vec = items + .iter() + .map(|item| { + let name = item.get("name").unwrap_or(&item["path"]); + let what = match (&item["added"], &item["removed"]) { + (Value::Number(added), Value::Number(removed)) => format!("+{added} -{removed}"), + _ => item["note"] + .as_str() + .or(item["error"].as_str()) + .unwrap_or_default() + .to_string(), + }; + format!( + "- {} {}: {what}", + item["type"].as_str().unwrap_or_default(), + name.as_str().unwrap_or_default() + ) + }) + .collect(); ctx.set_view( "windmill/review", - json!({ - "workspace": ctx.w_id, - "items": items, - // Windmill's own "Review & deploy drafts" page. - "url": ctx.page_url(&format!("/forks/compare?workspace_id={}&mode=draft", enc(ctx.w_id))), - }), + json!({ "workspace": ctx.w_id, "items": items, "url": review_url }), ); if total == 0 { return Ok("No drafts to review: nothing differs from the deployed state.".to_string()); } let mut text = format!( - "Showing {} draft(s) to the user, {reviewable} with a diff they can deploy from the card. Nothing was deployed: you are told when the user deploys one.", + "{} draft(s) to review, {reviewable} with a diff to deploy. Nothing was deployed. Where the card is drawn, the user deploys from it and you are told when they do.", items.len() ); if total > items.len() { @@ -2176,17 +2196,13 @@ pub(super) async fn show_deploy_review(ctx: &Ctx<'_>, args: &Value) -> ToolResul " Only the first {MAX_REVIEW_ITEMS} of {total} are shown." )); } - let rest: Vec<&str> = items - .iter() - .filter(|item| item.get("digest").is_none()) - .filter_map(|item| item.get("name").unwrap_or(&item["path"]).as_str()) - .collect(); - if !rest.is_empty() { - text.push_str(&format!( - " No Deploy is offered for {} (nothing to deploy, or not deployable from the card).", - rest.join(", ") - )); + for line in item_lines { + text.push_str(&format!("\n{line}")); } + text.push_str(&format!( + "\nReview and deploy in Windmill: {review_url}\n{}", + super::views::CARD_NOTE + )); Ok(text) } 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 f03e14dfa4..e0dd1ee8b8 100644 --- a/backend/windmill-api/src/ai_session_tools/gen/instructions.json +++ b/backend/windmill-api/src/ai_session_tools/gen/instructions.json @@ -308,7 +308,7 @@ "script.duckdb": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u//` when the user gave a bare name; only use `f//` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (duckdb)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_`, which keeps it apart from a hub type synced later: the parameter takes `RT.C` in TypeScript, a `c_` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n\n\n# DuckDB\n\nArguments are defined with comments and used with `$name` syntax:\n\n```sql\n-- $name (text) = default\n-- $age (integer)\nSELECT * FROM users WHERE name = $name AND age > $age;\n```\n\n## Ducklake Integration\n\nAttach Ducklake for data lake operations:\n\n```sql\n-- Main ducklake\nATTACH 'ducklake' AS dl;\n\n-- Named ducklake\nATTACH 'ducklake://my_lake' AS dl;\n\n-- Then query\nSELECT * FROM dl.schema.table;\n```\n\n## External Database Connections\n\nConnect to external databases using resources:\n\n```sql\nATTACH '$res:path/to/resource' AS db (TYPE postgres);\nSELECT * FROM db.schema.table;\n```\n\n## S3 File Operations\n\nRead files from S3 storage:\n\n```sql\n-- Default storage\nSELECT * FROM read_csv('s3:///path/to/file.csv');\n\n-- Named storage\nSELECT * FROM read_csv('s3://storage_name/path/to/file.csv');\n\n-- Parquet files\nSELECT * FROM read_parquet('s3:///path/to/file.parquet');\n\n-- JSON files\nSELECT * FROM read_json('s3:///path/to/file.json');\n```\n\n### Receiving an S3Object as a script parameter\n\nDeclare the arg with type `(s3object)`. Windmill renders an S3 file picker for it\nand binds the arg as the bare `s3://storage/key` URI, which DuckDB's reader\nfunctions consume directly:\n\n```sql\n-- $file (s3object)\nSELECT * FROM read_parquet($file);\n```\n\nWorks with any DuckDB reader: `read_csv($file)`, `read_json($file)`, etc.\n\n### Writing query results to S3\n\nDuckDB writes to S3 natively via `COPY ... TO`:\n\n```sql\nCOPY (SELECT * FROM users) TO 's3:///exports/users.parquet' (FORMAT PARQUET);\n```\n\nUse this instead of the `-- s3` streaming directive supported by the other SQL\ndialects — that directive is not available in DuckDB.\n", "script.bunnative": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u//` when the user gave a bare name; only use `f//` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (bunnative)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_`, which keeps it apart from a hub type synced later: the parameter takes `RT.C` in TypeScript, a `c_` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n\n\n# TypeScript (Bun Native)\n\nNative TypeScript execution. Native scripts are Bun scripts that run on the native worker — a lightweight V8 isolate that exposes `fetch` and the JavaScript standard library — and can be heavily parallelized. Every script MUST start with `//native` on its first line so Windmill routes it to the native worker; without it the exact same script runs on the regular Bun worker. You may import npm packages and other Windmill scripts (e.g. `./helper.ts`) — imports are resolved and bundled just like a regular Bun script — as long as everything (your code and its dependencies) relies only on `fetch` and the standard library. Libraries that need Node/Bun runtime APIs (filesystem, `node:*` modules, child processes, native addons) will not work on the native worker; use the regular `bun` language for those.\n\n## Structure\n\nExport a single **async** function called `main`:\n\n```typescript\n//native\nexport async function main(param1: string, param2: number) {\n // Your code here\n return { result: param1, count: param2 };\n}\n```\n\nDo not call the main function.\n\n## Resource Types\n\nOn Windmill, credentials and configuration are stored in resources and passed as parameters to main.\n\nUse the `RT` namespace for resource types:\n\n```typescript\n//native\nexport async function main(stripe: RT.Stripe) {\n // stripe contains API key and config from the resource\n}\n```\n\nOnly use resource types if you need them to satisfy the instructions. Always use the RT namespace.\n\n## Imports\n\n**The constraint is the runtime, not the import list.** You may import npm packages and relative Windmill scripts; they are resolved and bundled exactly like a regular Bun script. But the native worker only provides `fetch` and the JavaScript standard library, so any imported code must work using only those. Anything requiring Node/Bun built-ins (`node:fs`, `child_process`, the `Bun` API, native modules) belongs in a regular `bun` script instead. Use the globally available `fetch` for HTTP:\n\n```typescript\n//native\nexport async function main(url: string) {\n const response = await fetch(url);\n return await response.json();\n}\n```\n\n## Pure computation: `//no_network`\n\nA native script that only transforms its inputs can declare `//no_network` in its leading comment block (right after `//native`). The runtime then refuses every connection the script attempts: `fetch` to any host, the Windmill API (so `windmill-client` calls fail too), raw sockets and unix sockets, and `WM_TOKEN` is not set. Without `//native` it means something else: the script must run in an nsjail sandbox (`//sandbox`, or instance-wide sandboxing), which then loses its network, and it fails to run otherwise. Use it only when the script needs no external data beyond its arguments:\n\n```typescript\n//native\n//no_network\nexport async function main(items: { price: number; qty: number }[]) {\n return items.reduce((sum, i) => sum + i.price * i.qty, 0);\n}\n```\n\n## Windmill Client\n\n`windmill-client` works on the native worker (its calls go over `fetch`), so use it as the **preferred way to talk to Windmill** — reading resources/variables/states, running scripts and flows, and the S3 helpers below (`loadS3File`, `loadS3FileStream`, `writeS3File`, `S3Object`). It handles auth, the workspace, and the base URL for you. Reserve raw `fetch` for calling *external* HTTP APIs that aren't Windmill.\n\nThe full `windmill-client` API reference (every exported function and its signature) is included below — consult it for the exact method instead of hand-rolling a `fetch` against the Windmill API.\n\n## Preprocessor Scripts\n\nFor preprocessor scripts, the function should be named `preprocessor` and receives an `event` parameter:\n\n```typescript\n//native\ntype Event = {\n kind:\n | \"webhook\"\n | \"http\"\n | \"websocket\"\n | \"kafka\"\n | \"email\"\n | \"nats\"\n | \"postgres\"\n | \"sqs\"\n | \"mqtt\"\n | \"amqp\"\n | \"gcp\"\n | \"azure\";\n body: any;\n headers: Record;\n query: Record;\n};\n\nexport async function preprocessor(event: Event) {\n return {\n param1: event.body.field1,\n param2: event.query.id,\n };\n}\n```\n\n## S3 Object Operations\n\nWindmill provides built-in support for S3-compatible storage operations. The `wmill.S3Object` type covers both the `s3://storage/key` URI form (`s3:///key` for the workspace default storage) and the `{ s3, storage? }` record form — always use it instead of redefining your own.\n\n### Receiving an S3Object as a script parameter\n\n```typescript\n//native\nimport * as wmill from \"windmill-client\";\n\nexport async function main(file: wmill.S3Object) {\n const content = await wmill.loadS3File(file);\n // ...\n}\n```\n\n### S3 operations\n\n```typescript\n//native\nimport * as wmill from \"windmill-client\";\n\n// Load file content from S3\nconst content: Uint8Array = await wmill.loadS3File(s3object);\n\n// Load file as stream\nconst blob: Blob = await wmill.loadS3FileStream(s3object);\n\n// Write file to S3\nconst result: wmill.S3Object = await wmill.writeS3File(\n s3object, // Target path (or undefined to auto-generate)\n fileContent, // string or Blob\n s3ResourcePath // Optional: specific S3 resource to use\n);\n```\n\n\n# TypeScript SDK (windmill-client)\n\nImport: import * as wmill from 'windmill-client'\n\nThe client configures itself from the job's environment — base URL, token and credentials mode\nare all set before your code runs, so there is nothing to initialize and no reason to read\nWM_TOKEN or BASE_INTERNAL_URL and build an API URL yourself. Reconstructing that by hand only\nreintroduces details the client already handles. Call the SDK for anything Windmill, and use raw\nHTTP for third-party APIs.\n\nThe helpers below are the surface to prefer. For an endpoint none of them covers, import the\ngenerated service classes (JobService, ScriptService, ...) from 'windmill-client' — they are not\nlisted here but they do exist. What does not exist is a helper name you guessed at: if it is\nneither listed below nor a service method, do not call it.\n\nTo know who is running the script, read the contextual variables rather than calling the API:\n`process.env.WM_END_USER_EMAIL || process.env.WM_EMAIL`. WM_END_USER_EMAIL is the app viewer when\nthe run was triggered from an app and empty otherwise (both variables are always defined), WM_EMAIL\nis the user the job is permissioned as. WM_USERNAME is the matching username.\n\nworkerHasInternalServer(): boolean\n\n/**\n * Initialize the Windmill client with authentication token and base URL\n * @param token - Authentication token (defaults to WM_TOKEN env variable)\n * @param baseUrl - API base URL (defaults to BASE_INTERNAL_URL or BASE_URL env variable)\n */\nsetClient(token?: string, baseUrl?: string): void\n\n/**\n * Create a client configuration from env variables\n * @returns client configuration\n */\ngetWorkspace(): string\n\n/**\n * Get a resource value by path\n * @param path path of the resource, default to internal state path\n * @param undefinedIfEmpty if the resource does not exist, return undefined instead of throwing an error\n * @returns resource value\n */\nasync getResource(path?: string, undefinedIfEmpty?: boolean): Promise\n\n/**\n * Get the true root job id\n * @param jobId job id to get the root job id from (default to current job)\n * @returns root job id\n */\nasync getRootJobId(jobId?: string): Promise\n\n/**\n * Run a script synchronously by its path and wait for the result\n * @param path - Script path in Windmill\n * @param args - Arguments to pass to the script\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Script execution result\n */\nasync runScriptByPath(path: string, args: Record | null = null, verbose: boolean = false, tag: string | null = null): Promise\n\n/**\n * Run a script synchronously by its hash and wait for the result\n * @param hash_ - Script hash in Windmill\n * @param args - Arguments to pass to the script\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Script execution result\n */\nasync runScriptByHash(hash_: string, args: Record | null = null, verbose: boolean = false, tag: string | null = null): Promise\n\n/**\n * Append a text to the result stream\n * @param text text to append to the result stream\n */\nappendToResultStream(text: string): void\n\n/**\n * Stream to the result stream\n * @param stream stream to stream to the result stream\n */\nasync streamResult(stream: AsyncIterable): Promise\n\n/**\n * Run a flow synchronously by its path and wait for the result\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Flow execution result\n */\nasync runFlow(path: string | null = null, args: Record | null = null, verbose: boolean = false, tag: string | null = null): Promise\n\n/**\n * Wait for a job to complete and return its result\n * @param jobId - ID of the job to wait for\n * @param verbose - Enable verbose logging\n * @returns Job result when completed\n */\nasync waitJob(jobId: string, verbose: boolean = false): Promise\n\n/**\n * Get the result of a completed job\n * @param jobId - ID of the completed job\n * @returns Job result\n */\nasync getResult(jobId: string): Promise\n\n/**\n * Get the result of a job if completed, or its current status\n * @param jobId - ID of the job\n * @returns Object with started, completed, success, and result properties\n */\nasync getResultMaybe(jobId: string): Promise\n\n/**\n * Cancel a queued or running job by ID.\n * @param jobId - UUID of the job to cancel\n * @param reason - Optional reason for cancellation\n * @returns Response message from the cancel endpoint\n */\nasync cancelJob(jobId: string, reason: string | undefined = undefined): Promise\n\n/**\n * Run a script asynchronously by its path\n * @param path - Script path in Windmill\n * @param args - Arguments to pass to the script\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds), or {@link RunScriptAsyncOptions}\n * `{ scheduledInSeconds?, tag?, retry? }`, e.g. `{ retry: { constant: { attempts: 3, seconds: 10 } } }`\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runScriptByPathAsync(path: string, args: Record | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise\n\n/**\n * Run a script asynchronously by its hash\n * @param hash_ - Script hash in Windmill\n * @param args - Arguments to pass to the script\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds), or {@link RunScriptAsyncOptions}\n * `{ scheduledInSeconds?, tag?, retry? }`, e.g. `{ retry: { constant: { attempts: 3, seconds: 10 } } }`\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runScriptByHashAsync(hash_: string, args: Record | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise\n\n/**\n * Run a flow asynchronously by its path\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds)\n * @param doNotTrackInParent - If false, tracks state in parent job (only use when fully awaiting the job)\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runFlowAsync(path: string | null, args: Record | null, scheduledInSeconds: number | null = null, // can only be set to false if this the job will be fully await and not concurrent with any other job // as otherwise the child flow and its own child will store their state in the parent job which will // lead to incorrectness and failures doNotTrackInParent: boolean = true, tag: string | null = null): Promise\n\n/**\n * Run the deployed flow at `path` with some of its steps overridden, wait for it and return\n * its result. Meant for test scripts.\n * \n * Each entry of `steps` maps a step id to either:\n * - a value: the step is skipped and returns that value, or\n * - a function exported from the calling script's own file: the step runs that function\n * instead of its own code, with the step's inputs as arguments (matched by name).\n * \n * A step inside a subflow is named by the path of step ids to it, `\"sub:inner\"` for step `inner`\n * of the subflow that step `sub` calls. It applies to every call of that subflow made by the\n * tested flow and by the subflows it overrides; a subflow left as is still calls the deployed\n * one. Those subflows, and each one on the way to an override, run as you rather than as their\n * on-behalf-of identity. Result caching is off for the whole test run.\n * \n * The flow's preprocessor does not run: `args` are what the flow receives after it. A subflow\n * never runs its own preprocessor, in a test or not. AI agent\n * tools cannot be overridden; override the agent step instead.\n * \n * @example\n * export function fakeFetch(url: string) { return { status: 200 } }\n * export async function main() {\n * const result = await wmill.testFlow(\"f/flows/sync\", { user: \"a\" }, {\n * fetch_users: fakeFetch, // replaced logic\n * send_email: \"sent\", // mocked result\n * });\n * }\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param steps - Step id to mocked result, or to the function replacing the step\n * @param verbose - Enable verbose logging\n * @returns Flow execution result\n */\nasync testFlow(path: string, args: Record | null = null, steps: Record = {}, verbose: boolean = false): Promise\n\n/**\n * Like {@link testFlow}, but returns the job id without waiting for the flow to complete.\n */\nasync testFlowAsync(path: string, args: Record | null = null, steps: Record = {}): Promise\n\n/**\n * Resolve a resource value in case the default value was picked because the input payload was undefined\n * @param obj resource value or path of the resource under the format `$res:path`\n * @returns resource value\n */\nasync resolveDefaultResource(obj: any): Promise\n\n/**\n * Get the state file path from environment variables\n * @returns State path string\n */\ngetStatePath(): string\n\n/**\n * Set a resource value by path\n * @param path path of the resource to set, default to state path\n * @param value new value of the resource to set\n * @param initializeToTypeIfNotExist if the resource does not exist, initialize it with this type\n */\nasync setResource(value: any, path?: string, initializeToTypeIfNotExist?: string): Promise\n\n/**\n * Set the state\n * @param state state to set\n * @param path Optional state resource path override. Defaults to `getStatePath()`.\n */\nasync setState(state: any, path?: string): Promise\n\n/**\n * Set the progress\n * Progress cannot go back and limited to 0% to 99% range\n * @param percent Progress to set in %\n * @param jobId? Job to set progress for\n */\nasync setProgress(percent: number, jobId?: any): Promise\n\n/**\n * Get the progress\n * @param jobId? Job to get progress from\n * @returns Optional clamped between 0 and 100 progress value\n */\nasync getProgress(jobId?: any): Promise\n\n/**\n * Whether the worker running this job has received its shutdown signal.\n * A draining worker waits for its current job to finish before exiting, so a\n * long-running script can poll this and return early to let the worker be replaced.\n * @param jobId? Job to check, defaults to the current job\n */\nasync workerIsDraining(jobId?: string): Promise\n\n/**\n * Set a flow user state\n * @param key key of the state\n * @param value value of the state\n */\nasync setFlowUserState(key: string, value: any, errorIfNotPossible?: boolean): Promise\n\n/**\n * Get a flow user state\n * @param path path of the variable\n */\nasync getFlowUserState(key: string, errorIfNotPossible?: boolean): Promise\n\n/**\n * Get the state shared across executions\n * @param path Optional state resource path override. Defaults to `getStatePath()`.\n */\nasync getState(path?: string): Promise\n\n/**\n * Get a variable by path\n * @param path path of the variable\n * @returns variable value\n */\nasync getVariable(path: string): Promise\n\n/**\n * Set a variable by path, create if not exist\n * @param path path of the variable\n * @param value value of the variable\n * @param isSecretIfNotExist if the variable does not exist, create it as secret or not (default: false)\n * @param descriptionIfNotExist if the variable does not exist, create it with this description (default: \"\")\n */\nasync setVariable(path: string, value: string, isSecretIfNotExist?: boolean, descriptionIfNotExist?: string): Promise\n\n/**\n * Build a PostgreSQL connection URL from a database resource\n * @param path - Path to the database resource\n * @returns PostgreSQL connection URL string\n */\nasync databaseUrlFromResource(path: string): Promise\n\nasync polarsConnectionSettings(s3_resource_path: string | undefined): Promise\n\nasync duckdbConnectionSettings(s3_resource_path: string | undefined): Promise\n\n/**\n * Get S3 client settings from a resource or workspace default\n * @param s3_resource_path - Path to S3 resource (uses workspace default if undefined)\n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n * @returns S3 client configuration settings\n */\nasync denoS3LightClientSettings(s3_resource_path: string | undefined, workspace: string | undefined = undefined): Promise\n\n/**\n * Load the content of a file stored in S3. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * let fileContent = await wmill.loadS3FileContent(inputFile)\n * // if the file is a raw text file, it can be decoded and printed directly:\n * const text = new TextDecoder().decode(fileContentStream)\n * console.log(text);\n * ```\n * \n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n */\nasync loadS3File(s3object: S3Object, s3ResourcePath: string | undefined = undefined, workspace: string | undefined = undefined): Promise\n\n/**\n * Load the content of a file stored in S3 as a stream. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * let fileContentBlob = await wmill.loadS3FileStream(inputFile)\n * // if the content is plain text, the blob can be read directly:\n * console.log(await fileContentBlob.text());\n * ```\n * \n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n */\nasync loadS3FileStream(s3object: S3Object, s3ResourcePath: string | undefined = undefined, workspace: string | undefined = undefined): Promise\n\n/**\n * Persist a file to the S3 bucket. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * const s3object = await writeS3File(s3Object, \"Hello Windmill!\")\n * const fileContentAsUtf8Str = (await s3object.toArray()).toString('utf-8')\n * console.log(fileContentAsUtf8Str)\n * ```\n * \n * @param workspace - Workspace to write to (defaults to the `WM_WORKSPACE` env var)\n */\nasync writeS3File(s3object: S3Object | undefined, fileContent: string | Blob, s3ResourcePath: string | undefined = undefined, contentType: string | undefined = undefined, contentDisposition: string | undefined = undefined, workspace: string | undefined = undefined): Promise\n\n/**\n * Permanently delete a file from S3 by key.\n * \n * ```typescript\n * await wmill.deleteS3File({ s3: \"path/to/file.txt\" })\n * ```\n * \n * @param s3object - S3 object identifying the file to delete (must have `s3` set)\n * @param workspace - Workspace to delete from (defaults to the `WM_WORKSPACE` env var)\n */\nasync deleteS3File(s3object: S3Object, workspace: string | undefined = undefined): Promise\n\n/**\n * Sign S3 objects to be used by anonymous users in public apps\n * @param s3objects s3 objects to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed s3 objects\n */\nasync signS3Objects(s3objects: S3Object[], { expirySecs }: { expirySecs?: number } = {}): Promise\n\n/**\n * Sign S3 object to be used by anonymous users in public apps\n * @param s3object s3 object to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed s3 object\n */\nasync signS3Object(s3object: S3Object, { expirySecs }: { expirySecs?: number } = {}): Promise\n\n/**\n * Generate a presigned public URL for an array of S3 objects.\n * If an S3 object is not signed yet, it will be signed first.\n * @param s3Objects s3 objects to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns list of signed public URLs\n */\nasync getPresignedS3PublicUrls(s3Objects: S3Object[], { baseUrl, expirySecs }: { baseUrl?: string; expirySecs?: number } = {}): Promise\n\n/**\n * Generate a presigned public URL for an S3 object. If the S3 object is not signed yet, it will be signed first.\n * @param s3Object s3 object to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed public URL\n */\nasync getPresignedS3PublicUrl(s3Objects: S3Object, { baseUrl, expirySecs }: { baseUrl?: string; expirySecs?: number } = {}): Promise\n\n/**\n * Get URLs needed for resuming a flow after this step\n * @param approver approver name\n * @param flowLevel if true, generate resume URLs for the parent flow instead of the specific step.\n * This allows pre-approvals that can be consumed by any later suspend step in the same flow.\n * @returns approval page UI URL, resume and cancel API URLs for resuming the flow\n */\nasync getResumeUrls(approver?: string, flowLevel?: boolean): Promise<{\n approvalPage: string;\n resume: string;\n cancel: string;\n}>\n\n/**\n * Get an OIDC jwt token for auth to external services (e.g: Vault, AWS) (ee only)\n * @param audience audience of the token\n * @param expiresIn Optional number of seconds until the token expires\n * @returns jwt token\n */\nasync getIdToken(audience: string, expiresIn?: number): Promise\n\n/**\n * Convert a base64-encoded string to Uint8Array\n * @param data - Base64-encoded string\n * @returns Decoded Uint8Array\n */\nbase64ToUint8Array(data: string): Uint8Array\n\n/**\n * Convert a Uint8Array to base64-encoded string\n * @param arrayBuffer - Uint8Array to encode\n * @returns Base64-encoded string\n */\nuint8ArrayToBase64(arrayBuffer: Uint8Array): string\n\n/**\n * Sends an interactive approval request via Slack, allowing optional customization of the message, approver, and form fields.\n * \n * **[Enterprise Edition Only]** To include form fields in the Slack approval request, go to **Advanced -> Suspend -> Form**\n * and define a form. Learn more at [Windmill Documentation](https://www.windmill.dev/docs/flows/flow_approval#form).\n * \n * @param {Object} options - The configuration options for the Slack approval request.\n * @param {string} options.slackResourcePath - The path to the Slack resource in Windmill.\n * @param {string} options.channelId - The Slack channel ID where the approval request will be sent.\n * @param {string} [options.message] - Optional custom message to include in the Slack approval request.\n * @param {string} [options.approver] - Optional user ID or name of the approver for the request.\n * @param {DefaultArgs} [options.defaultArgsJson] - Optional object defining or overriding the default arguments to a form field.\n * @param {Enums} [options.dynamicEnumsJson] - Optional object overriding the enum default values of an enum form field.\n * @param {string} [options.resumeButtonText] - Optional text for the resume button.\n * @param {string} [options.cancelButtonText] - Optional text for the cancel button.\n * \n * @returns {Promise} Resolves when the Slack approval request is successfully sent.\n * \n * @throws {Error} If the function is not called within a flow or flow preview.\n * @throws {Error} If the `JobService.getSlackApprovalPayload` call fails.\n * \n * **Usage Example:**\n * ```typescript\n * await requestInteractiveSlackApproval({\n * slackResourcePath: \"/u/alex/my_slack_resource\",\n * channelId: \"admins-slack-channel\",\n * message: \"Please approve this request\",\n * approver: \"approver123\",\n * defaultArgsJson: { key1: \"value1\", key2: 42 },\n * dynamicEnumsJson: { foo: [\"choice1\", \"choice2\"], bar: [\"optionA\", \"optionB\"] },\n * resumeButtonText: \"Resume\",\n * cancelButtonText: \"Cancel\",\n * });\n * ```\n * \n * **Note:** This function requires execution within a Windmill flow or flow preview.\n */\nasync requestInteractiveSlackApproval({ slackResourcePath, channelId, message, approver, defaultArgsJson, dynamicEnumsJson, resumeButtonText, cancelButtonText, }: SlackApprovalOptions): Promise\n\n/**\n * Sends an interactive approval request via Teams, allowing optional customization of the message, approver, and form fields.\n * \n * **[Enterprise Edition Only]** To include form fields in the Teams approval request, go to **Advanced -> Suspend -> Form**\n * and define a form. Learn more at [Windmill Documentation](https://www.windmill.dev/docs/flows/flow_approval#form).\n * \n * @param {Object} options - The configuration options for the Teams approval request.\n * @param {string} options.teamName - The Teams team name where the approval request will be sent.\n * @param {string} options.channelName - The Teams channel name where the approval request will be sent.\n * @param {string} [options.message] - Optional custom message to include in the Teams approval request.\n * @param {string} [options.approver] - Optional user ID or name of the approver for the request.\n * @param {DefaultArgs} [options.defaultArgsJson] - Optional object defining or overriding the default arguments to a form field.\n * @param {Enums} [options.dynamicEnumsJson] - Optional object overriding the enum default values of an enum form field.\n * \n * @returns {Promise} Resolves when the Teams approval request is successfully sent.\n * \n * @throws {Error} If the function is not called within a flow or flow preview.\n * @throws {Error} If the `JobService.getTeamsApprovalPayload` call fails.\n * \n * **Usage Example:**\n * ```typescript\n * await requestInteractiveTeamsApproval({\n * teamName: \"admins-teams\",\n * channelName: \"admins-teams-channel\",\n * message: \"Please approve this request\",\n * approver: \"approver123\",\n * defaultArgsJson: { key1: \"value1\", key2: 42 },\n * dynamicEnumsJson: { foo: [\"choice1\", \"choice2\"], bar: [\"optionA\", \"optionB\"] },\n * });\n * ```\n * \n * **Note:** This function requires execution within a Windmill flow or flow preview.\n */\nasync requestInteractiveTeamsApproval({ teamName, channelName, message, approver, defaultArgsJson, dynamicEnumsJson, }: TeamsApprovalOptions): Promise\n\nsetWorkflowCtx(ctx: WorkflowCtx | null): void\n\nasync sleep(seconds: number): Promise\n\n/**\n * Execute `fn` inline and checkpoint the result. On replay the cached value is\n * returned without re-executing `fn`.\n * \n * `fn`'s result is encoded as JSON and decoded back before it is returned, so\n * the round that runs the body sees the same types every replay sees: a `Date`\n * comes back as a string, a `Map` as `{}`. {@link Jsonified} is that shape.\n * \n * Called from inside a task body, `fn` runs in place and nothing is\n * checkpointed: a task is a single job and is never replayed.\n */\nasync step(name: string, fn: () => T | Promise,): Promise>>\n\n/**\n * Create a task that dispatches to a separate Windmill script.\n * \n * @example\n * const extract = taskScript(\"f/data/extract\");\n * // inside workflow: await extract({ url: \"https://...\" })\n */\ntaskScript(path: string, options?: TaskOptions): (...args: any[]) => PromiseLike\n\n/**\n * Create a task that dispatches to a separate Windmill flow.\n * \n * @example\n * const pipeline = taskFlow(\"f/etl/pipeline\");\n * // inside workflow: await pipeline({ input: data })\n */\ntaskFlow(path: string, options?: TaskOptions): (...args: any[]) => PromiseLike\n\n/**\n * Mark an async function as a workflow-as-code entry point.\n * \n * The function must be **deterministic**: given the same inputs it must call\n * tasks in the same order on every replay. Branching on task results is fine\n * (results are replayed from checkpoint), but branching on external state\n * (current time, random values, external API calls) must use `step()` to\n * checkpoint the value so replays see the same result.\n */\nworkflow(fn: (...args: any[]) => Promise): void\n\n/**\n * Suspend the workflow and wait for an external approval.\n * \n * Pass `key` to name the step, then `getApprovalUrls(key)` yields the URLs that\n * resume exactly this approval — route them through your own channel. Without a\n * key the steps are named `approval`, `approval_2`, ...\n * \n * `skin: \"minimal\"` shows approvers only the request (form and approve/reject)\n * instead of the detailed page with the workflow's details. `description` is\n * shown above the form: a string, or a rich value such as `{ markdown: \"...\" }`.\n * \n * @example\n * const urls = await step(\"urls\", () => getApprovalUrls(\"manager\"));\n * await step(\"notify\", () => sendEmail(urls.resume, urls.cancel));\n * const { value, approver } = await waitForApproval({ key: \"manager\", timeout: 3600 });\n */\nwaitForApproval(options?: { timeout?: number; form?: object; selfApproval?: boolean; key?: string; skin?: \"detailed\" | \"minimal\"; description?: string | object; }): PromiseLike<{ value: any; approver: string; approved: boolean }>\n\n/**\n * Resume/cancel/approval-page URLs bound to one `waitForApproval` step.\n * \n * Unlike `getResumeUrls()`, which signs a random nonce, these address the very\n * `resume_job` record the step's built-in approval buttons use, so they are\n * stable across replays and safe to embed in a custom notification.\n * \n * `stepKey` must match the `key` given to `waitForApproval`. Keys must be unique\n * within a workflow; reusing one throws rather than silently renaming it. The URL\n * only resumes while that step is awaiting approval; used at any other moment it is\n * rejected rather than banking a row a different approval would consume. Send it\n * ahead of time — approvers just cannot act before the workflow reaches the step.\n * \n * `resume` and `cancel` are step-bound; `approvalPage` is not — it opens the job's\n * approval page, which acts on whichever approval is pending when it is used.\n * \n * @example\n * const urls = await step(\"urls\", () => getApprovalUrls(\"manager\"));\n * await step(\"notify\", () => sendEmail(urls.resume, urls.cancel));\n * await waitForApproval({ key: \"manager\" });\n */\nasync getApprovalUrls(stepKey: string = \"approval\", approver?: string): Promise<{\n approvalPage: string;\n resume: string;\n cancel: string;\n}>\n\n/**\n * Process items in parallel with optional concurrency control.\n * \n * Each item is processed by calling `fn(item)`, which should be a task().\n * Items are dispatched in batches of `concurrency` (default: all at once).\n * \n * @example\n * const process = task(async (item: string) => { ... });\n * const results = await parallel(items, process, { concurrency: 5 });\n */\nasync parallel(items: T[], fn: (item: T) => PromiseLike | R, options?: { concurrency?: number },): Promise\n\n/**\n * Commit Kafka offsets for a trigger with auto_commit disabled.\n * @param triggerPath - Path to the Kafka trigger (from event.wm_trigger.trigger_path)\n * @param topic - Kafka topic name (from event.topic)\n * @param partition - Partition number (from event.partition)\n * @param offset - Message offset to commit (from event.offset)\n */\nasync commitKafkaOffsets(triggerPath: string, topic: string, partition: number, offset: number,): Promise\n\n/**\n * Parse an S3 object from URI string or record format\n * @param s3Object - S3 object as URI string (`s3://storage/key`, `s3:///key`\n * for the default storage) or record. Any other string throws rather than\n * falling back to an auto-generated key: an auto key is requested by\n * omitting the object, and a fallback would silently misplace the upload\n * on any typo.\n * @returns S3 object record with storage and s3 key\n */\nparseS3Object(s3Object: S3Object): S3ObjectRecord\n\n/**\n * Create a SQL template function for PostgreSQL/datatable queries\n * @param name - Database/datatable name (default: \"main\")\n * @param opts.role - Connect as this data table role instead of the data table's default one.\n * Only meaningful on a data table under roles, and only for a role you are a tenant of.\n * @returns SQL template function for building parameterized queries\n * @example\n * let sql = wmill.datatable()\n * let name = 'Robin'\n * let age = 21\n * await sql`\n * SELECT * FROM friends\n * WHERE name = ${name} AND age = ${age}::int\n * `.fetch()\n * @example\n * // Read through a restricted role\n * let sql = wmill.datatable(\"main\", { role: \"analytics\" })\n */\ndatatable(name: string = \"main\", opts?: DatatableOptions): DatatableSqlTemplateFunction\n\n/**\n * Create a SQL template function for DuckDB/ducklake queries\n * @param name - DuckDB database name, optionally with a schema as `name:schema` (default: \"main\")\n * @returns SQL template function for building parameterized queries\n * @example\n * let sql = wmill.ducklake()\n * let name = 'Robin'\n * let age = 21\n * await sql`\n * SELECT * FROM friends\n * WHERE name = ${name} AND age = ${age}\n * `.fetch()\n * @example\n * // Target a specific schema within the ducklake\n * let sql = wmill.ducklake(\"my_lake:analytics\")\n */\nducklake(name: string = \"main\"): SqlTemplateFunction\n\n/**\n * Idempotently materialize `selectSql` into a ducklake table for one\n * partition (or the whole table when `partition` is omitted) — the client-side\n * equivalent of the `// materialize` engine.\n * With `uniqueKey` it upserts the slice (delete-by-key + insert); otherwise it\n * replaces it (whole table → `CREATE OR REPLACE`; partition → delete + insert).\n * Safe to re-run for the same partition (backfill / failure-recovery).\n * \n * Returns a lazy statement — call `.execute()` to run it:\n * `await wmill.upsertPartition({ table, selectSql, partition }).execute()`.\n */\nupsertPartition(opts: DucklakeMaterializeOptions): SqlStatement\n\n/**\n * INSERT-only materialization (no dedup/replace) for append-only tables.\n * Re-running the same partition duplicates rows — use only for immutable\n * event-log sources.\n * \n * Returns a lazy statement — call `.execute()` to run it:\n * `await wmill.appendPartition({ table, selectSql, partition }).execute()`.\n */\nappendPartition(opts: Omit,): SqlStatement\n", "script.dbt": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u//` when the user gave a bare name; only use `f//` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (dbt)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters\n- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_`, which keeps it apart from a hub type synced later: the parameter takes `RT.C` in TypeScript, a `c_` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it\n- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration\n- Libraries are installed automatically - do not show installation instructions\n- In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n", - "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, on_concurrency_limit, 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, timeout, 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. Set `background: true` on a `flowmodule` tool that runs long: the agent is\nanswered as soon as its job starts and keeps working, and gets the result in a later message,\nwaiting for it without holding a worker if it finishes its answer first. Prefer it to having the\nagent start jobs through a script or `runScriptByPath`, whose results it cannot wait on. For a tool\nthat is usually quick but sometimes long, set `background_after_secs: ` instead: the agent\nwaits that long for the result, then the call continues in the background.\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 or Gemini'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), `openai` (`model` `gpt-6-luna`, never a\n chat model) or `googleai` (`model` `gemini-decision-1`, never a chat model); the resource is of\n 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- On `googleai` the `questions` and answers are the same as on `typesafe`. If Gemini blocks the\n input, the step fails. A `state` that is a Gemini content block or an array of them (`[{ type: \"text\", text }, { type: \"image\", mime_type: \"image/png\", data: \"\" }]`,\n where `image`, `audio`, `video` and `document` blocks take `data` or `uri`) is sent as is, which\n is how an image or a document 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, plus `reason` on a disapproval whose approver gave one\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- When iterations are items a user will look for in a run (customers, files, ids), set `iteration_label` on the `forloopflow` value to a javascript expression naming each one, e.g. `flow_input.iter.value.name`; it only labels iterations in the run viewer and never changes what runs\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- To cap a `whileloopflow`, set `max_iterations` and/or `max_duration_secs` (seconds since the first iteration started) on the loop's `value`, rather than encoding the bound into `stop_after_if`. Both are checked after each iteration, so a running iteration is never interrupted and the loop can exceed `max_duration_secs` by at most one iteration (bound an iteration with its steps' `timeout`); whichever is reached first, unless `stop_after_if` stopped the loop at that iteration, fails the loop with `{ error: { name: \"LoopExhausted\", message } }`. To handle it, set `continue_on_error: true` on the loop and branch in the next step on `results..error?.name === \"LoopExhausted\"` (only the step right after the loop sees the error there; later steps see the iterations' results); retries and the failure module apply as for any step failure. For a pause between iterations, set `sleep` on the body's step\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\"},\"on_concurrency_limit\":{\"type\":\"string\",\"enum\":[\"queue\",\"fail\"],\"description\":\"What a run of this flow does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed, like any failed step.\"},\"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\"},\"timeout\":{\"type\":\"integer\",\"description\":\"Wall-clock limit in seconds for the whole flow run, counted from its start and including time spent sleeping or suspended at an approval. It also applies when the flow is called as a subflow step, unless that step sets its own timeout, which replaces it. It is checked periodically, so a run can go a few seconds past it. When it expires, the running steps are cancelled, the failure module runs if there is one, and the flow ends cancelled with a timeout error. A calling flow sees the subflow step fail with that error.\"},\"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\"},\"preview_only\":{\"type\":\"boolean\",\"description\":\"If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run.\"}}},\"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\"},\"on_concurrency_limit\":{\"type\":\"string\",\"enum\":[\"queue\",\"fail\"],\"description\":\"What a run of this step does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed.\"},\"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')\"},\"tag_override\":{\"type\":\"string\",\"description\":\"Override the subflow's worker group tag. Its steps run on this tag unless the subflow sets preserve_step_tags\"},\"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\"},\"iteration_label\":{\"description\":\"Optional expression evaluated once per iteration into the label the run viewers show for it, e.g. 'flow_input.iter.value.name'. It can reference 'flow_input.iter' and 'results'. Purely informational, a failing expression leaves the iteration unlabelled and never fails it. Labels are capped at 100 characters\",\"$ref\":\"#/components/schemas/InputTransform\"}},\"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\"},\"max_iterations\":{\"type\":\"integer\",\"minimum\":1,\"description\":\"Maximum number of iterations. Checked after each iteration; when reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'\"},\"max_duration_secs\":{\"type\":\"integer\",\"minimum\":1,\"description\":\"Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'\"}},\"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\"},\"parallelism\":{\"description\":\"Maximum number of branches running at once when parallel=true. Can be static number or expression\",\"$ref\":\"#/components/schemas/InputTransform\"}},\"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.\"},\"background\":{\"type\":\"boolean\",\"description\":\"Flowmodule tools only. The agent is answered as soon as the tool's job starts and keeps working; the job's result reaches it in a later message. If the agent finishes its answer first, it stops without holding a worker until the job is done, then continues with the result.\"},\"background_after_secs\":{\"type\":\"integer\",\"minimum\":1,\"description\":\"Flowmodule tools only, with background unset. The agent waits up to this many seconds for the tool's job and gets its result as usual; a job still running then continues as a background one, its result reaching the agent in a later message.\"},\"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 or Gemini'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\"}}}},\"continued_on_error\":{\"type\":\"array\",\"description\":\"On a root flow, the steps at any depth that failed and that the flow went past because of continue_on_error (at most 100).\",\"items\":{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\"},\"job\":{\"type\":\"string\",\"format\":\"uuid\"}},\"required\":[\"id\",\"job\"]}},\"test_subflows\":{\"type\":\"object\",\"description\":\"In a flow test run, deployed subflow path -> the flow value with the test's step overrides applied, run in place of the deployed subflow.\",\"additionalProperties\":{\"type\":\"object\"}}},\"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_labels\":{\"type\":\"array\",\"description\":\"For a for-loop step whose iteration_label is set, each iteration's label, aligned with flow_jobs. An entry is null when its label evaluated to nothing\",\"items\":{\"type\":\"string\",\"nullable\":true}},\"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\",\"description\":\"The outcome of each agent action, by position. null while a background tool call is still running.\",\"items\":{\"type\":\"boolean\",\"nullable\":true}}},\"required\":[\"type\"]}}", + "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, on_concurrency_limit, 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, timeout, 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. Set `background: true` on a `flowmodule` tool that runs long: the agent is\nanswered as soon as its job starts and keeps working, and gets the result in a later message,\nwaiting for it without holding a worker if it finishes its answer first. Prefer it to having the\nagent start jobs through a script or `runScriptByPath`, whose results it cannot wait on. For a tool\nthat is usually quick but sometimes long, set `background_after_secs: ` instead: the agent\nwaits that long for the result, then the call continues in the background.\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 or Gemini'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), `openai` (`model` `gpt-6-luna`, never a\n chat model) or `googleai` (`model` `gemini-decision-1`, never a chat model); the resource is of\n 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- On `googleai` the `questions` and answers are the same as on `typesafe`. If Gemini blocks the\n input, the step fails. A `state` that is a Gemini content block or an array of them (`[{ type: \"text\", text }, { type: \"image\", mime_type: \"image/png\", data: \"\" }]`,\n where `image`, `audio`, `video` and `document` blocks take `data` or `uri`) is sent as is, which\n is how an image or a document 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, plus `reason` on a disapproval whose approver gave one\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- To carry on past failed iterations only up to a budget (e.g. a rollout over many targets), set `skip_failures: true` with `failure_threshold` on the `forloopflow` or `whileloopflow` value: the loop fails with `{ error: { name: \"FailureThresholdReached\", message } }` once that many iterations have failed. It takes a whole number of at least 1, or an input transform evaluated once when the loop starts that returns one, e.g. `{ type: \"javascript\", expr: \"Math.ceil(flow_input.targets.length * 0.1)\" }` for 10%. A parallel loop then cancels the iterations no worker has picked up yet, including those held back by `parallelism`, while iterations already picked up finish, so set `parallelism` to bound how many are in flight when the threshold is reached\n- When iterations are items a user will look for in a run (customers, files, ids), set `iteration_label` on the `forloopflow` value to a javascript expression naming each one, e.g. `flow_input.iter.value.name`; it only labels iterations in the run viewer and never changes what runs\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- To cap a `whileloopflow`, set `max_iterations` and/or `max_duration_secs` (seconds since the first iteration started) on the loop's `value`, rather than encoding the bound into `stop_after_if`. Both are checked after each iteration, so a running iteration is never interrupted and the loop can exceed `max_duration_secs` by at most one iteration (bound an iteration with its steps' `timeout`); whichever is reached first, unless `stop_after_if` stopped the loop at that iteration, fails the loop with `{ error: { name: \"LoopExhausted\", message } }`. To handle it, set `continue_on_error: true` on the loop and branch in the next step on `results..error?.name === \"LoopExhausted\"` (only the step right after the loop sees the error there; later steps see the iterations' results); retries and the failure module apply as for any step failure. For a pause between iterations, set `sleep` on the body's step\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\"},\"on_concurrency_limit\":{\"type\":\"string\",\"enum\":[\"queue\",\"fail\"],\"description\":\"What a run of this flow does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed, like any failed step.\"},\"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\"},\"timeout\":{\"type\":\"integer\",\"description\":\"Wall-clock limit in seconds for the whole flow run, counted from its start and including time spent sleeping or suspended at an approval. It also applies when the flow is called as a subflow step, unless that step sets its own timeout, which replaces it. It is checked periodically, so a run can go a few seconds past it. When it expires, the running steps are cancelled, the failure module runs if there is one, and the flow ends cancelled with a timeout error. A calling flow sees the subflow step fail with that error.\"},\"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\"},\"preview_only\":{\"type\":\"boolean\",\"description\":\"If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run.\"}}},\"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\"},\"show_on_home\":{\"type\":\"boolean\",\"description\":\"If true, a run waiting on this step is listed on the Home page of each user who can approve it. Leave unset when the approval request is sent through another channel (Slack, Discord, email), so it does not sit there unanswered\"}}},\"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\"},\"on_concurrency_limit\":{\"type\":\"string\",\"enum\":[\"queue\",\"fail\"],\"description\":\"What a run of this step does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed.\"},\"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')\"},\"tag_override\":{\"type\":\"string\",\"description\":\"Override the subflow's worker group tag. Its steps run on this tag unless the subflow sets preserve_step_tags\"},\"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\"},\"failure_threshold\":{\"description\":\"With skip_failures, the loop fails with an error named 'FailureThresholdReached' as soon as this many iterations have failed. Static number or expression (e.g. 'Math.ceil(flow_input.targets.length * 0.1)' for a percentage), evaluated once when the loop starts. A sequential loop stops at the iteration that reaches it. A parallel loop cancels the iterations no worker has picked up yet, including those held back by parallelism, while iterations already picked up finish; set parallelism to bound how many are in flight when the threshold is reached\",\"$ref\":\"#/components/schemas/InputTransform\"},\"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\"},\"iteration_label\":{\"description\":\"Optional expression evaluated once per iteration into the label the run viewers show for it, e.g. 'flow_input.iter.value.name'. It can reference 'flow_input.iter' and 'results'. Purely informational, a failing expression leaves the iteration unlabelled and never fails it. Labels are capped at 100 characters\",\"$ref\":\"#/components/schemas/InputTransform\"}},\"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\"},\"max_iterations\":{\"type\":\"integer\",\"minimum\":1,\"description\":\"Maximum number of iterations. Checked after each iteration; when reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'\"},\"max_duration_secs\":{\"type\":\"integer\",\"minimum\":1,\"description\":\"Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'\"},\"failure_threshold\":{\"description\":\"With skip_failures, the loop fails with an error named 'FailureThresholdReached' at the iteration that brings the failed iterations to this count. Static number or expression, evaluated once when the loop starts\",\"$ref\":\"#/components/schemas/InputTransform\"}},\"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\"},\"parallelism\":{\"description\":\"Maximum number of branches running at once when parallel=true. Can be static number or expression\",\"$ref\":\"#/components/schemas/InputTransform\"}},\"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.\"},\"background\":{\"type\":\"boolean\",\"description\":\"Flowmodule tools only. The agent is answered as soon as the tool's job starts and keeps working; the job's result reaches it in a later message. If the agent finishes its answer first, it stops without holding a worker until the job is done, then continues with the result.\"},\"background_after_secs\":{\"type\":\"integer\",\"minimum\":1,\"description\":\"Flowmodule tools only, with background unset. The agent waits up to this many seconds for the tool's job and gets its result as usual; a job still running then continues as a background one, its result reaching the agent in a later message.\"},\"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 or Gemini'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\"}}}},\"continued_on_error\":{\"type\":\"array\",\"description\":\"On a root flow, the steps at any depth that failed and that the flow went past because of continue_on_error (at most 100).\",\"items\":{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\"},\"job\":{\"type\":\"string\",\"format\":\"uuid\"}},\"required\":[\"id\",\"job\"]}},\"test_subflows\":{\"type\":\"object\",\"description\":\"In a flow test run, deployed subflow path -> the flow value with the test's step overrides applied, run in place of the deployed subflow.\",\"additionalProperties\":{\"type\":\"object\"}}},\"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_labels\":{\"type\":\"array\",\"description\":\"For a for-loop step whose iteration_label is set, each iteration's label, aligned with flow_jobs. An entry is null when its label evaluated to nothing\",\"items\":{\"type\":\"string\",\"nullable\":true}},\"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\"},\"approved_at\":{\"type\":\"string\",\"format\":\"date-time\",\"description\":\"absent for approvals recorded before it was kept\"},\"approved\":{\"type\":\"boolean\",\"description\":\"false for a rejection the flow continued past; absent for approvals recorded before it was kept\\n\"}},\"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\",\"description\":\"The outcome of each agent action, by position. null while a background tool call is still running.\",\"items\":{\"type\":\"boolean\",\"nullable\":true}}},\"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- Connecting a service (a resource with a secret field) happens in one `request_secret` call, not in an editor or with `write_resource`:\n 1. Ask only what shapes the card and the user has not said: where the service is hosted (e.g. Supabase, Neon, RDS). A Postgres card takes a connection string or the details, and the user picks there; `connection_string: true` opens it on the string. Never ask for a value the card takes (a host, a user, a database name, a region): put each field you do not know in `resource_value` as an empty string, and the user fills it on the card. Default what has a sensible default.\n 2. Call `request_secret` with `resource_type`, a resource path you checked is free (list the resources and variables near it first), the non-secret fields you prepared as `resource_value`, and every secret field in `secret_fields`. It returns a link to a Windmill page where the user types the secrets: give them the link, and once they say it is saved, check that the resource draft exists and use its `$res:` path. Do not write that resource yourself.\n 3. The card saves drafts, and every run, test runs and connection tests included, reads only deployed items. Before running anything that uses the resource, offer to deploy it with its secret variables; when the user only wanted it saved, end by offering that deploy.\n 4. Never ask for a secret in the conversation, and never create a secret variable with a placeholder or empty value for the user to fill in. A secret that goes into no resource (a run argument) is a `request_secret` without `resource_type`.\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- When the user has not given you the secret, they enter it in Windmill's secure input, never in the conversation.\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**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### Styling\n\nPlain CSS imported from the entrypoint (`import './index.css'`) is bundled as is. For **Tailwind CSS v4**, add `tailwindcss` (`^4`) to `package.json` and start `index.css` with `@import \"tailwindcss\";`: the bundler then compiles it, generating the utilities used in the app's files and in the workspace's shared `/ui` folder, along with `@theme`, `@utility`, `@apply` and `@custom-variant`. A design system's stylesheet can live in `/ui` and be imported with `@import \"/ui/theme.css\";`. There is no `tailwind.config.js`: configure Tailwind in CSS. `@plugin` and `@config` are compiled only by the CLI (`wmill app bundle` / `wmill app push`), not by the web editor, and `wmill app dev` must be restarted to pick up an edit to one of them or to a file they import. Without the `tailwindcss` dependency, Tailwind directives are left uncompiled.\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 * Run the deployed flow at `path` with some of its steps overridden, wait for it and return\n * its result. Meant for test scripts.\n * \n * Each entry of `steps` maps a step id to either:\n * - a value: the step is skipped and returns that value, or\n * - a function exported from the calling script's own file: the step runs that function\n * instead of its own code, with the step's inputs as arguments (matched by name).\n * \n * A step inside a subflow is named by the path of step ids to it, `\"sub:inner\"` for step `inner`\n * of the subflow that step `sub` calls. It applies to every call of that subflow made by the\n * tested flow and by the subflows it overrides; a subflow left as is still calls the deployed\n * one. Those subflows, and each one on the way to an override, run as you rather than as their\n * on-behalf-of identity. Result caching is off for the whole test run.\n * \n * The flow's preprocessor does not run: `args` are what the flow receives after it. A subflow\n * never runs its own preprocessor, in a test or not. AI agent\n * tools cannot be overridden; override the agent step instead.\n * \n * @example\n * export function fakeFetch(url: string) { return { status: 200 } }\n * export async function main() {\n * const result = await wmill.testFlow(\"f/flows/sync\", { user: \"a\" }, {\n * fetch_users: fakeFetch, // replaced logic\n * send_email: \"sent\", // mocked result\n * });\n * }\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param steps - Step id to mocked result, or to the function replacing the step\n * @param verbose - Enable verbose logging\n * @returns Flow execution result\n */\nasync testFlow(path: string, args: Record<string, any> | null = null, steps: Record<string, any> = {}, verbose: boolean = false): Promise<any>\n\n/**\n * Like {@link testFlow}, but returns the job id without waiting for the flow to complete.\n */\nasync testFlowAsync(path: string, args: Record<string, any> | null = null, steps: Record<string, any> = {}): 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### Styling\n\nPlain CSS imported from the entrypoint (`import './index.css'`) is bundled as is. For **Tailwind CSS v4**, add `tailwindcss` (`^4`) to `package.json` and start `index.css` with `@import \"tailwindcss\";`: the bundler then compiles it, generating the utilities used in the app's files and in the workspace's shared `/ui` folder, along with `@theme`, `@utility`, `@apply` and `@custom-variant`. A design system's stylesheet can live in `/ui` and be imported with `@import \"/ui/theme.css\";`. There is no `tailwind.config.js`: configure Tailwind in CSS. `@plugin` and `@config` are compiled only by the CLI (`wmill app bundle` / `wmill app push`), not by the web editor, and `wmill app dev` must be restarted to pick up an edit to one of them or to a file they import. Without the `tailwindcss` dependency, Tailwind directives are left uncompiled.\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# retry_transient: Retry on 429 and 502-504 with exponential backoff, honoring\n# Retry-After. Pass False for an endpoint with a side effect.\n# retry_budget: Most seconds to spend sleeping between retries (at most 15)\n# **kwargs: Additional arguments passed to httpx.get\n# \n# Returns:\n# HTTP response object\ndef get(endpoint, raise_for_status = True, *, retry_transient: bool = True, retry_budget: float | None = None, **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# Start the deployed flow at ``path`` with some steps overridden and return its job id.\n# \n# See ``test_flow`` for ``steps``.\ndef test_flow_async(path: str, args: dict = None, steps: dict = None) -> str\n\n# Run the deployed flow at ``path`` with some steps overridden and return its result.\n# \n# See the module-level ``test_flow``.\ndef test_flow(path: str, args: dict = None, steps: dict = None, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, assert_result_is_not_none: bool = False) -> Any\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", @@ -317,8 +317,8 @@ "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", "datatable.go": "# 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\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", "pipeline": "# Data pipeline authoring\n\nA **data pipeline** is NOT a flow. A flow is one runnable that orchestrates steps internally. A data pipeline is a set of **independent scripts**, each deployed on its own, that form a DAG by reading and writing shared **storage assets** (DuckLake tables, data tables, S3 objects, volumes, resources) and by declaring execution **triggers**. The pipeline is visualized and edited at `/pipeline/<folder>`; every node is a normal workspace script that happens to carry pipeline annotations. When the user asks for a \"data pipeline\" (or to \"ingest / transform / materialize\" data across steps), build pipeline-annotated scripts — do NOT build a flow.\n\n## Default to DuckDB + DuckLake\n\nA pipeline node that produces a table should almost always be a **`duckdb`** node that materializes its output into a **DuckLake** table with `-- materialize ducklake://<name>/<table>` (in a DuckDB node the annotation uses SQL `--` comment syntax; write the body as a bare `SELECT` and let the runtime do the write). DuckLake is the default lakehouse store for pipelines and is the shape the pipeline editor is built around, so prefer it unless the work specifically calls for something else:\n\n- `postgresql` / data tables — only for row-level, OLTP-style mutations against an existing Postgres data table (frequent single-row upserts/updates, transactional reads that an app queries live).\n- `bun` / `python3` — only for work that doesn't map to SQL: calling an external API, wrangling files, arbitrary glue. When such a node produces tabular data for downstream steps, write it **straight into DuckLake** (or a data table) from the same script — see \"Ingesting from Python / TypeScript\" below — rather than inventing a parallel store.\n\nDo not spread a pipeline across postgres, S3, and DuckLake when one DuckLake lake would do; a consistent DuckLake lakehouse is the goal.\n\n## Ingesting from Python / TypeScript\n\nA node that fetches data in code (an API, a SaaS export, a scraper) writes the rows **directly** into their DuckLake table with `wmill.ducklake()`, or into a data table with `wmill.datatable()`. DuckLake already stores every table as parquet files in the workspace object storage, so **never stage the raw payload first** — no intermediate JSON / CSV / parquet file in S3 and no second \"load the raw file\" node. One ingestion node, one table.\n\nPass the rows as a query argument (a list of dicts / array of objects is sent as JSON) and let SQL unnest them; declare the column types so the table gets a real schema:\n\n```python\n# pipeline\n# on schedule\nimport wmill\n\ndef main():\n rows = fetch_charges() # list[dict]\n lake = wmill.ducklake()\n lake.query(\"\"\"\n CREATE OR REPLACE TABLE stripe_charges AS\n SELECT unnest(from_json($rows, '[{\"id\":\"VARCHAR\",\"amount\":\"BIGINT\",\"created\":\"BIGINT\"}]'), recursive := true)\n \"\"\", rows=rows).fetch()\n```\n\n```ts\n// pipeline\n// on schedule\nimport * as wmill from \"windmill-client\"\n\nexport async function main() {\n const rows = await fetchCharges()\n const lake = wmill.ducklake()\n await lake`CREATE OR REPLACE TABLE stripe_charges AS\n SELECT unnest(from_json(${rows}, '[{\"id\":\"VARCHAR\",\"amount\":\"BIGINT\",\"created\":\"BIGINT\"}]'), recursive := true)`.fetch()\n}\n```\n\n- Use `INSERT INTO <table> SELECT ...` instead of `CREATE OR REPLACE` to append (an incremental pull), with a one-time `CREATE TABLE IF NOT EXISTS` first.\n- Assign the client to a variable (`lake = wmill.ducklake()`) and keep the SQL a **string literal** (Python) or a template without `sql.raw` (TS): that is what lets the graph record the node's write to `ducklake://main/<table>`. A chained `wmill.ducklake().query(...)` or SQL built in a variable records no output, so the downstream edge never forms.\n- `wmill.ducklake(\"<name>\")` targets a non-default catalog; `wmill.datatable(\"<name>\")` writes a Postgres data table the same way (Python `db.query(sql, *args)` with `$1` placeholders, TS the same template form) — use it only when the data belongs in Postgres (see above).\n- The downstream node triggers on the table itself: `-- on ducklake://main/stripe_charges`.\n\n## Storage prerequisites\n\nA DuckLake pipeline only runs once the workspace has **object storage** (S3 / Azure Blob / GCS) **and a DuckLake catalog** configured — DuckLake tables and `s3://` assets can't be materialized or read without it. Check which DuckLake catalogs the workspace has before you build.\nDrafting the annotated scripts does not require storage, but the pipeline can't ingest, materialize, or read its assets until it exists. So if there is none (or the user hits \"storage not configured\" errors), say so and give the right next step **by role**:\n\n- a workspace **admin** sets it up in Workspace settings → Object Storage (add an S3/Azure/GCS storage), then adds a DuckLake catalog on top of it;\n- anyone **without admin rights** should ask a workspace admin to configure object storage + a DuckLake catalog.\n\nNever hand back a DuckLake pipeline that cannot run without flagging the missing storage and pointing to who sets it up.\n\n## What makes a script a pipeline node\n\nA script joins the pipeline when its source begins with the `pipeline` annotation as a top-of-file comment, **written in the script's own comment syntax** — `//` for TS/JS (bun), `--` for SQL (DuckDB/Postgres), `#` for Python/Bash. So it's `-- pipeline` in a DuckDB node, `# pipeline` in a Python node, `// pipeline` in a bun node. Every annotation below uses that same prefix (the `//` shown is the TS form). All other wiring is expressed as annotation comments near the top of the file:\n\n- `// on <ref>` — declares an execution-DAG **input** (what triggers/feeds this node). `<ref>` is either:\n - an **asset URI** (the node runs when that asset is produced upstream): `ducklake://main/orders`, `datatable://main/users`, `$res:f/folder/my_resource`, `volume://name/path`, or an S3 object (see the S3 storage-form rule below).\n - a **native trigger kind**: `schedule`, `webhook`, `email`, `kafka`, `mqtt`, `amqp`, `nats`, `postgres`, `sqs`, `gcp`, or `data_upload` (a user-uploaded S3 file). For these the actual trigger row (cron, topic, …) is created separately; the annotation only declares the binding. **`data_upload` is special**: there is no trigger row — the node instead declares an **`S3Object` input parameter** fed by the auto-generated upload picker; it never hard-codes a key. Any language can be the `data_upload` node:\n - Python (has `import wmill`): `def main(file: wmill.S3Object):` then `wmill.load_s3_file(file)`; TS (has `import * as wmill from \"windmill-client\"`): `export async function main(file: wmill.S3Object)`. Qualify the type as `wmill.S3Object` (or add `from wmill import S3Object` / `import { S3Object } from \"windmill-client\"`) — a bare `S3Object` is undefined.\n - **DuckDB** takes the s3object arg via a `-- $<name> (s3object)` declaration and reads it directly, so a single DuckDB node can ingest **and** materialize:\n ```\n -- pipeline\n -- on data_upload\n -- materialize ducklake://main/raw_uploads\n -- $file (s3object)\n SELECT * FROM read_csv($file)\n ```\n- **Outputs** are inferred from what the body writes — a `CREATE TABLE`, a `wmill.writeS3File(...)`, a DuckLake/datatable write. To declare a managed output explicitly, use `// materialize <asset-uri>`.\n- Optional badges: `// partitioned <daily|hourly|weekly|monthly|dynamic>`, `// freshness <duration>` (e.g. `1h`), `// tag <worker-tag>`, `// retry <count> [delay]`, `// data_test <kind> ...` (managed DuckLake targets only — deploy rejects it beside a `dbt://` one), `// measure <name> = <agg> [where <pred>]` and `// dimension <name> = <expr>` (see \"Declared metrics\" below).\n\n## S3 object wiring (storage form matters)\n\nAn `s3://` URI's first slashes select the **storage**, not part of the key — get this wrong and the producer/consumer edge silently won't connect:\n\n- `s3:///<key>` (**triple** slash, empty first segment) = the **default** workspace storage. A downstream node reading or triggering on that object uses `s3:///<key>` — e.g. DuckDB `-- on s3:///orders/2024.parquet` and `read_parquet('s3:///orders/2024.parquet')`.\n- `s3://<storage>/<key>` (**double** slash, non-empty first segment) = a **named secondary** storage called `<storage>` — so `s3://ingest/x` means storage `ingest`, key `x`, NOT key `ingest/x`. Only use this when the object genuinely lives in a configured secondary storage; never invent a bucket/storage name for a default-storage object (it breaks the edge).\n\nTo make the producer side visible to lineage, a Python/TS node MUST pass the **`S3Object` form**, not a bare key string: Python `wmill.write_s3_file(wmill.S3Object(s3=\"<key>\"), data)` (or the import-free dict `{\"s3\": \"<key>\"}`), TS `wmill.writeS3File({ s3: \"<key>\" }, data)`. That records the default-storage asset `/<key>`, which a downstream `s3:///<key>` reader connects to (same key both sides). A bare `write_s3_file(\"<key>\", ...)` records **no** asset and produces **no** edge. Add `storage=\"<name>\"` only for a named secondary storage.\n\nThe key must be a **string literal** — the graph parser is static and cannot follow a variable, f-string, or computed path, so `write_s3_file(wmill.S3Object(s3=key_var), ...)` records no edge. Inline the literal (`s3=\"events/user_events.parquet\"`) on both the writing and reading node. The same rule applies to every asset URI in an annotation or SDK call (`ducklake://`, `datatable://`, `s3://`): write them literally, not via a variable.\n\n## Materialize (the managed output)\n\n> **A MANAGED `// materialize` is DuckDB-only**, and its target must be a DuckLake table (`ducklake://<name>/<table>`). Deploy **rejects** a `ducklake://` `// materialize` on any other language (`python3`, `bun`, `postgresql`). For a non-DuckDB node writing the lake, do **not** use `// materialize` — write the table itself with `wmill.ducklake()` (see \"Ingesting from Python / TypeScript\") and let the output be inferred. Use `duckdb` when a node should materialize a DuckLake table.\n>\n> The one target ANY language may declare (except a dbt script, whose writes come from its manifest) is a **warehouse relation**: `// materialize manual dbt://<warehouse>/<schema>/<name>`, where `<warehouse>` is a warehouse the workspace configures under Settings → dbt. `manual` is the only mode it has — nothing generates warehouse DDL, so the node issues its own write (a postgresql `CREATE TABLE` / `INSERT`, an SDK load, …) and the annotation records the outcome. Use it on an ingestion node whose output a dbt project reads as a `source`: the declared relation and the dbt model land on ONE graph node, and a downstream `// on dbt://<warehouse>/<schema>/<name>` fires when the ingestion node completes.\n\nA managed `// materialize ducklake://<name>/<table>` tells the runtime to write the node's output table **for you**: write the body as a single `SELECT` and the runtime wraps it in the create/replace — do **not** also write your own `CREATE TABLE` / `INSERT`. (The opposite holds for the `dbt://` target above: there the node writes its own DDL and the strategies below do not apply.)\n\nA target that names no table — `// materialize`, `// materialize ducklake://<name>`, or options alone such as `// materialize key=id` — writes the table named after the script: node `f/shop/orders_daily` materializes `ducklake://main/orders_daily` (characters other than letters, digits and `_` become `_`, and a name starting with a digit gets a leading `_`). Name the node after the table it produces and the bare form is enough; write the full target when the table's name differs from the node's, and use that same name in every downstream `// on` and read.\n\nWrite strategy:\n\n- no option → **replace** the whole table each run (full refresh; the only mode whose output columns may change);\n- `// materialize <uri> append` → INSERT-append rows (incremental);\n- `// materialize <uri> key=<col>` → merge/upsert on `<col>`.\n\n`// materialize manual <uri>` opts **out** of managed writes — the script writes its own DDL and the annotation only records the output asset for lineage.\n\n`materialize` pairs with partitioning for incremental pipelines: a `// partitioned <daily|hourly|weekly|monthly|dynamic>` node runs **once per partition** (append/merge into a fixed-schema table). The `{partition}` token, usable in any asset URI **and** in the body SQL, is replaced at run time by the current partition's **identity string**:\n\n- To filter the source to the active slice on a time grain, use the runtime-injected macro: `WHERE wm_partition(<ts_col>) = {partition}`. `wm_partition(ts)` buckets a timestamp in exactly the identity format the runtime uses for daily/hourly/weekly/monthly, so it always matches; never hand-write a `strftime` format.\n- Do NOT write `= TIMESTAMP {partition}`: the identity string is not a valid timestamp literal for hourly/weekly/monthly and errors at run time.\n- For `dynamic` partitioning the identity is the caller-supplied key (not a timestamp, no macro), so filter on it directly: `WHERE <your_key_col> = {partition}`.\n\n`materialize` is an output **declaration** on a node — not a command. There is no \"materialize run\".\n\n## Declared metrics (`measure` / `dimension`)\n\nOn a node that materializes a DuckLake table, `// measure <name> = <aggregate> [where <predicate>]` names the canonical way to aggregate that table (e.g. `// measure revenue = sum(amount) where not is_refund`), and `// dimension <name> = <expr>` names a way to slice it (e.g. `// dimension region = region`, `// dimension month = date_trunc('month', ordered_at)`). They execute nothing: they are catalogued at deploy so the editor and other agents reuse the definition instead of re-deriving it and silently disagreeing.\n\n- Keep the predicate in the `where` clause rather than folding it into the aggregate: it is rendered as `<agg> FILTER (WHERE <pred>)`, which is what lets two measures with different predicates share one GROUP BY.\n- DuckLake-only, and only meaningful next to `// materialize`.\n- Declare one when a number carries a judgement call someone else would get wrong (refunds excluded, test rows dropped, which column is the amount); do NOT blanket every table with measures — an obvious `count(*)` earns nothing.\n- To use a metric another node declares, read that node and reuse its exact expression rather than guessing it.\n\n## How to build one\n\n1. Put every node in the **same folder**: `f/<folder>/<name>`. The folder is the pipeline.\n2. Write each node as its own script. Default to `duckdb` materializing into DuckLake (see \"Default to DuckDB + DuckLake\" above); pick `postgresql`, `bun`, or `python3` only when that section says the work calls for it.\n3. Start each body with `// pipeline`, then the `// on` input declarations, then the transform that writes the output.\n4. **Chain nodes by asset URI**: read an upstream node's output asset, then `// on <that-same-uri>` in the downstream node so the edge forms. Reuse exact asset paths from existing nodes rather than inventing parallel ones.\n5. Never guess the columns of a file or table you have not seen: read them first with a query that writes nothing, such as `DESCRIBE SELECT * FROM read_csv('s3:///raw/orders/*.csv')` or `ATTACH 'ducklake://main' AS lake; DESCRIBE lake.orders`, and use those exact column names. A test run of a node that materializes a table writes that table into the workspace's lake: test-run such a node only while its table does not exist yet, and ask before running one that would replace a table already there.\n6. Don't deploy nodes unless the user asks to. A pipeline only \"runs\" once its scripts are deployed and their triggers exist.\n\n## Example (DuckDB → DuckLake, scheduled ingest + downstream transform)\n\nNode `f/sales/orders_ingest` (runs on a schedule, materializes a DuckLake table):\n\n```sql\n-- pipeline\n-- on schedule\n-- materialize ducklake://main/orders\nSELECT * FROM read_csv('s3:///raw/orders/*.csv')\n```\n\nNode `f/sales/orders_daily` (runs when `orders` is produced, writes a rollup):\n\n```sql\n-- pipeline\n-- on ducklake://main/orders\n-- materialize ducklake://main/orders_daily\nATTACH 'ducklake://main' AS lake;\nSELECT date_trunc('day', ts) AS day, count(*) AS n\nFROM lake.orders GROUP BY 1\n```\n\nA node reads a DuckLake table only through a lake it attaches itself (`ATTACH 'ducklake://<name>' AS lake;`, then `lake.<table>`); the materialize target is attached by the runtime under a name of its own, so `ducklake.main.<table>` does not resolve.\n", - "workspace_settings": "# Workspace settings\n\nEverything an admin sets on the Workspace settings page is one document: a mapping of top-level\nkeys, the same layout as the `settings.yaml` file `wmill sync` keeps. Only a workspace admin can\nread or change it.\n\n## Applying a document\n\n- A partial document changes only the keys it states; every key it omits is left as it is.\n- Each key is replaced whole, so read its current value and send it back edited: a nested object\n given with one field replaces the stored object with that one field.\n- A key set to `null` clears that setting; an on/off switch cleared this way reads as `false`.\n- Each setting is written through the same path the settings page uses, with the same validation\n and audit log. The writes are not one transaction: when one fails the apply stops, and the\n error says what was already written.\n- A dry run reports the changes, as `before` / `after` per key, without writing anything.\n- `name` is never applied: rename a workspace on the settings page. `color` is applied only when\n set to a value, so `null` does not clear it.\n- A key the server does not know is ignored and named in the warnings: check them, since a typo\n otherwise reads as \"nothing to change\".\n- A setting this edition does not offer (Enterprise only) is refused, by the dry run too.\n\n## Secrets\n\n`webhook` (its URL usually carries the receiver's token) and `slack_oauth_client_secret` are the\nsecrets. A read shows `__SENSITIVE_AND_UNCHANGED__` in place\nof a set secret; sending that placeholder back keeps the stored value. A value starting with\n`$encrypted:` is decrypted with the workspace key, and one encrypted with another workspace's key\nis left unchanged with a warning; any other value is taken as plaintext. Never\nwrite a secret you were not given: keep the placeholder.\n\n## Keys\n\n| Key | Value |\n|---|---|\n| `auto_invite` | `{ enabled, mode: invite \\| add, operator, instance_groups?, instance_groups_roles? }`. The instance groups are managed only when `instance_groups` is stated; clearing a group removes the members it added. |\n| `error_handler` / `success_handler` | `{ path, extra_args?, muted_on_cancel?, muted_on_user_path?, muted_on_ui_runs? }`, `path` being `script/<path>` or `flow/<path>`. `muted_on_ui_runs` (error handler only) skips jobs started from the UI. |\n| `error_handler_fallback_to_instance_alerts` | Report failures to the instance critical alert channels when no error handler is set. |\n| `webhook` | URL POSTed a JSON event on every change to the workspace's items. |\n| `ai_config` | Providers, default and completion models, custom prompts, `copilot_disabled`. |\n| `large_file_storage` | Workspace object storage: `{ type, s3_resource_path \\| azure_blob_resource_path \\| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }`. |\n| `git_sync` | `{ repositories: [...] }`, each with `git_repo_resource_path`, `script_path` and `settings` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. |\n| `datatable` | `{ datatables: { <name>: { database: { resource_type, resource_path } } } }`, both required: `resource_type: postgresql` with `resource_path` a Postgres resource's path, or `instance`, or `external_instance` (Enterprise only), with `resource_path` the name of a database a superadmin set up. A fork's entry can instead be `{ reference: { workspace_id, datatable } }`, pointing at its parent's data table; keep it as is. `main` is the one scripts use by default. Role permissions are `datatable_permissions`. |\n| `datatable_permissions` | `{ <data table>: { default_role, roles: { <role>: [tenants] } } }`: who may connect to each data table as which role. Tenants are `u/<user>`, `g/<group>`, `f/<folder>` or `*`; `admin` is always a role, and `default_role: null` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. |\n| `protection_rules` | `{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { <role here>: <role in its forks> } } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. |\n| `ducklake` | `{ ducklakes: { <name>: { catalog, storage, ... } } }`. |\n| `dbt_warehouses` | dbt warehouse connections. |\n| `default_app` | Path of the app shown as the workspace home. |\n| `default_scripts` | `{ order?, hidden?, default_script_content? }` for the script language picker. |\n| `deploy_ui` | `{ include_path?, include_type? }`: what the deploy-to-workspace UI offers. |\n| `role_overrides` | `{ <role>: { label?, capabilities, workspace_only? } }`: the workspace's overrides of the instance's roles, and with `workspace_only: true` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in `role_overrides.operator`. |\n| `operator_settings` | Legacy view of the `operator` role, kept for older servers: page visibility flags (`runs`, `schedules`, `resources`, `variables`, `assets`, `audit_logs`, `groups`, `folders`, `workers`, `triggers`) and write rights (`manage_schedules`, `manage_triggers`, `builder_flows`, `builder_apps`). Not applied when the document also states `role_overrides`. |\n| `mute_critical_alerts` | Mute the workspace's critical alerts. |\n| `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. |\n| `slack_command_script` / `teams_command_script` | Script or flow handling the Slack / Teams command. |\n| `slack_oauth_client_id` / `slack_oauth_client_secret` | The workspace's own Slack OAuth app. Clearing either removes both. |\n| `public_app_execution_limit_per_minute` | Rate limit for public apps, `null` for none. |\n| `guest_jwt_public_key`, `guest_jwt_jwks_url` | The key that signs guest JWTs for apps set to Guests. |\n| `add_admins_and_developers_to_forks` | Add the workspace's admins and developers to each fork. |\n| `color` | Workspace color, `#rrggbb`. |\n", - "display": "# Rich results\n\nWindmill renders a script's or flow's return value according to its shape: on run pages, in the\nscript and flow editors, in app result displays and in AI chat run cards. Anything that matches none\nof the shapes below is shown as JSON.\n\n## Shapes\n\n- `{ \"table-row-object\": [{...}, ...] }`, or a bare array of objects: a table whose columns are the\n union of the objects' keys.\n- `{ \"table-col\": { \"col\": [...], ... } }`, or a bare object of equal-length arrays: a table built\n column by column.\n- `{ \"table-row\": [[\"col\", ...], [v, ...], ...] }`: a table whose first row holds the column names.\n- `{ \"chart\": {...} }`: a bar, line, pie or scatter chart drawn from rows (schema below). A `chart`\n value the schema rejects is shown as JSON, not as a broken chart.\n- `{ \"markdown\": \"...\" }` (or `md`): rendered markdown.\n- `{ \"html\": \"...\" }`: sanitized HTML.\n- `{ \"png\": \"<base64>\" }`, likewise `jpeg`, `gif`, `svg`: an image. `{ \"pdf\": \"<base64>\" }`: a PDF.\n- `{ \"file\": \"<base64>\", \"filename\": \"report.csv\" }`: a download.\n- `{ \"map\": { \"lat\": 0, \"lon\": 0, \"zoom\": 3, \"markers\": [{ \"lat\": 0, \"lon\": 0, \"title\": \"...\" }] } }`:\n a map.\n- `{ \"s3\": \"path/to/key\" }`: an object in the workspace storage, previewed by type.\n- `{ \"render_all\": [ ... ] }`: each item rendered in turn with the rules above.\n\nEach shape is an object with that one key (plus `filename` for a file, and an optional `storage` for\n`s3`). A result carrying any other key beside it is shown as JSON.\n\n## Choosing one\n\nA chart answers a question at a glance: a trend over time (line), a comparison across categories\n(bar), parts of a whole with few parts (pie), or a relation between two numbers (scatter). A table\nanswers lookups and holds the exact values. When both help, return both in a `render_all`: the chart\nfirst, then the table of the same rows.\n\nKeep a chart to what it shows well: at most 8 series. A pie with more than 8 slices keeps the 7\nlargest and folds the rest into \"Other\", so prefer a bar chart for many categories. Aggregate before\ncharting: a chart of thousands of raw points says less than one of the totals per day.\n\n\n### Chart and table schema\n\nA chart or table value, as JSON Schema. Beyond it: `x` and every `y` must be columns of `data`, `y` columns hold numbers, a scatter chart's `x` column holds numbers, and a pie chart takes exactly one `y`.\n\n```json\n{\"$schema\":\"https://json-schema.org/draft/2020-12/schema\",\"anyOf\":[{\"anyOf\":[{\"type\":\"object\",\"properties\":{\"chart\":{\"type\":\"object\",\"properties\":{\"type\":{\"description\":\"bar or line for categories or time, pie for parts of a whole, scatter for two numeric columns\",\"type\":\"string\",\"enum\":[\"bar\",\"line\",\"pie\",\"scatter\"]},\"title\":{\"type\":\"string\"},\"data\":{\"description\":\"The rows to plot, the same shape as a table-row-object result\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}},\"x\":{\"description\":\"Column holding the category, label or date of each row (bar, line, pie), or the numeric x value (scatter)\",\"type\":\"string\"},\"y\":{\"description\":\"Numeric column, or columns, to plot: one series each. A pie takes exactly one\",\"anyOf\":[{\"type\":\"string\"},{\"minItems\":1,\"maxItems\":8,\"type\":\"array\",\"items\":{\"type\":\"string\"}}]},\"stacked\":{\"description\":\"bar and line: stack the series\",\"type\":\"boolean\"},\"horizontal\":{\"description\":\"bar: draw the bars horizontally\",\"type\":\"boolean\"},\"x_label\":{\"type\":\"string\"},\"y_label\":{\"type\":\"string\"}},\"required\":[\"type\",\"data\",\"x\",\"y\"],\"additionalProperties\":false}},\"required\":[\"chart\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row-object\":{\"description\":\"Rows as objects; the columns are the union of their keys\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row-object\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-col\":{\"description\":\"Columns: column name to its values, all the same length\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"maxItems\":5000,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-col\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row\":{\"description\":\"Rows as arrays; the first row holds the column names\",\"minItems\":2,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row\"],\"additionalProperties\":false}]},{\"type\":\"object\",\"properties\":{\"render_all\":{\"description\":\"Several items shown one after another\",\"minItems\":1,\"maxItems\":10,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"object\",\"properties\":{\"chart\":{\"type\":\"object\",\"properties\":{\"type\":{\"description\":\"bar or line for categories or time, pie for parts of a whole, scatter for two numeric columns\",\"type\":\"string\",\"enum\":[\"bar\",\"line\",\"pie\",\"scatter\"]},\"title\":{\"type\":\"string\"},\"data\":{\"description\":\"The rows to plot, the same shape as a table-row-object result\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}},\"x\":{\"description\":\"Column holding the category, label or date of each row (bar, line, pie), or the numeric x value (scatter)\",\"type\":\"string\"},\"y\":{\"description\":\"Numeric column, or columns, to plot: one series each. A pie takes exactly one\",\"anyOf\":[{\"type\":\"string\"},{\"minItems\":1,\"maxItems\":8,\"type\":\"array\",\"items\":{\"type\":\"string\"}}]},\"stacked\":{\"description\":\"bar and line: stack the series\",\"type\":\"boolean\"},\"horizontal\":{\"description\":\"bar: draw the bars horizontally\",\"type\":\"boolean\"},\"x_label\":{\"type\":\"string\"},\"y_label\":{\"type\":\"string\"}},\"required\":[\"type\",\"data\",\"x\",\"y\"],\"additionalProperties\":false}},\"required\":[\"chart\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row-object\":{\"description\":\"Rows as objects; the columns are the union of their keys\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row-object\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-col\":{\"description\":\"Columns: column name to its values, all the same length\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"maxItems\":5000,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-col\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row\":{\"description\":\"Rows as arrays; the first row holds the column names\",\"minItems\":2,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row\"],\"additionalProperties\":false}]}}},\"required\":[\"render_all\"],\"additionalProperties\":false}]}\n```\n\nBar chart, one series per y column:\n\n```json\n{\n \"chart\": {\n \"type\": \"bar\",\n \"title\": \"Runs per day\",\n \"data\": [\n {\n \"day\": \"2026-11-10\",\n \"success\": 42,\n \"failure\": 3\n },\n {\n \"day\": \"2026-11-11\",\n \"success\": 51,\n \"failure\": 1\n }\n ],\n \"x\": \"day\",\n \"y\": [\n \"success\",\n \"failure\"\n ],\n \"stacked\": true\n }\n}\n```\n\nPie chart (exactly one y column):\n\n```json\n{\n \"chart\": {\n \"type\": \"pie\",\n \"data\": [\n {\n \"language\": \"python3\",\n \"scripts\": 18\n },\n {\n \"language\": \"bun\",\n \"scripts\": 25\n }\n ],\n \"x\": \"language\",\n \"y\": \"scripts\"\n }\n}\n```\n\nA chart and a table together:\n\n```json\n{\n \"render_all\": [\n {\n \"chart\": {\n \"type\": \"line\",\n \"data\": [\n {\n \"hour\": \"10:00\",\n \"p95_ms\": 120\n },\n {\n \"hour\": \"11:00\",\n \"p95_ms\": 180\n }\n ],\n \"x\": \"hour\",\n \"y\": \"p95_ms\",\n \"y_label\": \"ms\"\n }\n },\n {\n \"table-row-object\": [\n {\n \"hour\": \"10:00\",\n \"p95_ms\": 120,\n \"jobs\": 310\n },\n {\n \"hour\": \"11:00\",\n \"p95_ms\": 180,\n \"jobs\": 402\n }\n ]\n }\n ]\n}\n```\n", + "workspace_settings": "# Workspace settings\n\nEverything an admin sets on the Workspace settings page is one document: a mapping of top-level\nkeys, the same layout as the `settings.yaml` file `wmill sync` keeps. Only a workspace admin can\nread or change it.\n\n## Applying a document\n\n- A partial document changes only the keys it states; every key it omits is left as it is.\n- Each key is replaced whole, so read its current value and send it back edited: a nested object\n given with one field replaces the stored object with that one field.\n- A key set to `null` clears that setting; an on/off switch cleared this way reads as `false`.\n- Each setting is written through the same path the settings page uses, with the same validation\n and audit log. The writes are not one transaction: when one fails the apply stops, and the\n error says what was already written.\n- A dry run reports the changes, as `before` / `after` per key, without writing anything.\n- `name` is never applied: rename a workspace on the settings page. `color` is applied only when\n set to a value, so `null` does not clear it.\n- A key the server does not know is ignored and named in the warnings: check them, since a typo\n otherwise reads as \"nothing to change\".\n- A setting this edition does not offer (Enterprise only) is refused, by the dry run too.\n\n## Secrets\n\n`webhook` (its URL usually carries the receiver's token) and `slack_oauth_client_secret` are the\nsecrets. A read shows `__SENSITIVE_AND_UNCHANGED__` in place\nof a set secret; sending that placeholder back keeps the stored value. A value starting with\n`$encrypted:` is decrypted with the workspace key, and one encrypted with another workspace's key\nis left unchanged with a warning; any other value is taken as plaintext. Never\nwrite a secret you were not given: keep the placeholder.\n\n## Keys\n\n| Key | Value |\n|---|---|\n| `auto_invite` | `{ enabled, mode: invite \\| add, operator, instance_groups?, instance_groups_roles? }`. The instance groups are managed only when `instance_groups` is stated; clearing a group removes the members it added. |\n| `error_handler` / `success_handler` | `{ path, extra_args?, muted_on_cancel?, muted_on_user_path?, muted_on_ui_runs? }`, `path` being `script/<path>` or `flow/<path>`. `muted_on_ui_runs` (error handler only) skips jobs started from the UI. |\n| `error_handler_fallback_to_instance_alerts` | Report failures to the instance critical alert channels when no error handler is set. |\n| `webhook` | URL POSTed a JSON event on every change to the workspace's items. |\n| `ai_config` | Providers, default and completion models, custom prompts, `copilot_disabled`. |\n| `large_file_storage` | Workspace object storage: `{ type, s3_resource_path \\| azure_blob_resource_path \\| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }`. |\n| `git_sync` | `{ repositories: [...] }`, each with `git_repo_resource_path`, `script_path` and `settings` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. |\n| `datatable` | `{ datatables: { <name>: { database: { resource_type, resource_path } } } }`, both required: `resource_type: postgresql` with `resource_path` a Postgres resource's path, or `instance`, or `external_instance` (Enterprise only), with `resource_path` the name of a database a superadmin set up. A fork's entry can instead be `{ reference: { workspace_id, datatable } }`, pointing at its parent's data table; keep it as is. `main` is the one scripts use by default. Role permissions are `datatable_permissions`. |\n| `datatable_permissions` | `{ <data table>: { default_role, roles: { <role>: [tenants] } } }`: who may connect to each data table as which role. Tenants are `u/<user>`, `g/<group>`, `f/<folder>` or `*`; `admin` is always a role, and `default_role: null` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. |\n| `protection_rules` | `{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { <role here>: <role in its forks> } } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`, `RequireSso` (an account signing in with a password, other than a bypasser, cannot join, and no member can be switched to a password login; members already signing in with a password are not removed). A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. |\n| `ducklake` | `{ ducklakes: { <name>: { catalog, storage, ... } } }`. |\n| `dbt_warehouses` | dbt warehouse connections. |\n| `default_app` | Path of the app shown as the workspace home. |\n| `default_scripts` | `{ order?, hidden?, default_script_content? }` for the script language picker. |\n| `deploy_ui` | `{ include_path?, include_type? }`: what the deploy-to-workspace UI offers. |\n| `role_overrides` | `{ <role>: { label?, capabilities, workspace_only? } }`: the workspace's overrides of the instance's roles, and with `workspace_only: true` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in `role_overrides.operator`. |\n| `operator_settings` | Legacy view of the `operator` role, kept for older servers: page visibility flags (`runs`, `schedules`, `resources`, `variables`, `assets`, `audit_logs`, `groups`, `folders`, `workers`, `triggers`) and write rights (`manage_schedules`, `manage_triggers`, `builder_flows`, `builder_apps`). Not applied when the document also states `role_overrides`. |\n| `mute_critical_alerts` | Mute the workspace's critical alerts. |\n| `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. |\n| `slack_command_script` / `teams_command_script` | Script or flow handling the Slack / Teams command. |\n| `slack_oauth_client_id` / `slack_oauth_client_secret` | The workspace's own Slack OAuth app. Clearing either removes both. |\n| `public_app_execution_limit_per_minute` | Rate limit for public apps, `null` for none. |\n| `guest_jwt_public_key`, `guest_jwt_jwks_url` | The key that signs guest JWTs for apps set to Guests. |\n| `add_admins_and_developers_to_forks` | Add the workspace's admins and developers to each fork. |\n| `color` | Workspace color, `#rrggbb`. |\n", + "display": "# Rich results\n\nWindmill renders a script's or flow's return value according to its shape: on run pages, in the\nscript and flow editors, in app result displays and in AI chat run cards. Anything that matches none\nof the shapes below is shown as JSON.\n\n## Shapes\n\n- `{ \"table-row-object\": [{...}, ...] }`, or a bare array of objects: a table whose columns are the\n union of the objects' keys.\n- `{ \"table-col\": { \"col\": [...], ... } }`, or a bare object of equal-length arrays: a table built\n column by column.\n- `{ \"table-row\": [[\"col\", ...], [v, ...], ...] }`: a table whose first row holds the column names.\n- `{ \"chart\": {...} }`: a bar, line, pie or scatter chart drawn from rows (schema below). A `chart`\n value the schema rejects is shown as JSON, not as a broken chart.\n- `{ \"markdown\": \"...\" }` (or `md`): rendered markdown.\n- `{ \"html\": \"...\" }`: sanitized HTML.\n- `{ \"png\": \"<base64>\" }`, likewise `jpeg`, `gif`, `svg`: an image. `{ \"pdf\": \"<base64>\" }`: a PDF.\n- `{ \"file\": \"<base64>\", \"filename\": \"report.csv\" }`: a download.\n- `{ \"map\": { \"lat\": 0, \"lon\": 0, \"zoom\": 3, \"markers\": [{ \"lat\": 0, \"lon\": 0, \"title\": \"...\" }] } }`:\n a map.\n- `{ \"s3\": \"path/to/key\" }`: an object in the workspace storage, previewed by type.\n- `{ \"render_all\": [ ... ] }`: each item rendered in turn with the rules above.\n\nEach shape is an object with that one key (plus `filename` for a file, and an optional `storage` for\n`s3`). A result carrying any other key beside it is shown as JSON.\n\n## Large results\n\nA result stored above about 90 KB is not sent with the run: the run page and the editors offer it\nas a JSON download, with a Load button that draws it on request. A `render_all` lists up to 100 of\nits elements with their type and size, counts the rest, and loads them ten at a time. To have a large result previewed without a\nclick, write the content to the workspace storage and return `{ \"s3\": \"path/to/key\" }`, which is\npreviewed by type; for a generated image, also keep it small (a JPEG, or fewer pixels) when it only\nneeds to be looked at.\n\n## Choosing one\n\nA chart answers a question at a glance: a trend over time (line), a comparison across categories\n(bar), parts of a whole with few parts (pie), or a relation between two numbers (scatter). A table\nanswers lookups and holds the exact values. When both help, return both in a `render_all`: the chart\nfirst, then the table of the same rows.\n\nKeep a chart to what it shows well: at most 8 series. A pie with more than 8 slices keeps the 7\nlargest and folds the rest into \"Other\", so prefer a bar chart for many categories. Aggregate before\ncharting: a chart of thousands of raw points says less than one of the totals per day.\n\n\n### Chart and table schema\n\nA chart or table value, as JSON Schema. Beyond it: `x` and every `y` must be columns of `data`, `y` columns hold numbers, a scatter chart's `x` column holds numbers, and a pie chart takes exactly one `y`.\n\n```json\n{\"$schema\":\"https://json-schema.org/draft/2020-12/schema\",\"anyOf\":[{\"anyOf\":[{\"type\":\"object\",\"properties\":{\"chart\":{\"type\":\"object\",\"properties\":{\"type\":{\"description\":\"bar or line for categories or time, pie for parts of a whole, scatter for two numeric columns\",\"type\":\"string\",\"enum\":[\"bar\",\"line\",\"pie\",\"scatter\"]},\"title\":{\"type\":\"string\"},\"data\":{\"description\":\"The rows to plot, the same shape as a table-row-object result\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}},\"x\":{\"description\":\"Column holding the category, label or date of each row (bar, line, pie), or the numeric x value (scatter)\",\"type\":\"string\"},\"y\":{\"description\":\"Numeric column, or columns, to plot: one series each. A pie takes exactly one\",\"anyOf\":[{\"type\":\"string\"},{\"minItems\":1,\"maxItems\":8,\"type\":\"array\",\"items\":{\"type\":\"string\"}}]},\"stacked\":{\"description\":\"bar and line: stack the series\",\"type\":\"boolean\"},\"horizontal\":{\"description\":\"bar: draw the bars horizontally\",\"type\":\"boolean\"},\"x_label\":{\"type\":\"string\"},\"y_label\":{\"type\":\"string\"}},\"required\":[\"type\",\"data\",\"x\",\"y\"],\"additionalProperties\":false}},\"required\":[\"chart\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row-object\":{\"description\":\"Rows as objects; the columns are the union of their keys\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row-object\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-col\":{\"description\":\"Columns: column name to its values, all the same length\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"maxItems\":5000,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-col\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row\":{\"description\":\"Rows as arrays; the first row holds the column names\",\"minItems\":2,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row\"],\"additionalProperties\":false}]},{\"type\":\"object\",\"properties\":{\"render_all\":{\"description\":\"Several items shown one after another\",\"minItems\":1,\"maxItems\":10,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"object\",\"properties\":{\"chart\":{\"type\":\"object\",\"properties\":{\"type\":{\"description\":\"bar or line for categories or time, pie for parts of a whole, scatter for two numeric columns\",\"type\":\"string\",\"enum\":[\"bar\",\"line\",\"pie\",\"scatter\"]},\"title\":{\"type\":\"string\"},\"data\":{\"description\":\"The rows to plot, the same shape as a table-row-object result\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}},\"x\":{\"description\":\"Column holding the category, label or date of each row (bar, line, pie), or the numeric x value (scatter)\",\"type\":\"string\"},\"y\":{\"description\":\"Numeric column, or columns, to plot: one series each. A pie takes exactly one\",\"anyOf\":[{\"type\":\"string\"},{\"minItems\":1,\"maxItems\":8,\"type\":\"array\",\"items\":{\"type\":\"string\"}}]},\"stacked\":{\"description\":\"bar and line: stack the series\",\"type\":\"boolean\"},\"horizontal\":{\"description\":\"bar: draw the bars horizontally\",\"type\":\"boolean\"},\"x_label\":{\"type\":\"string\"},\"y_label\":{\"type\":\"string\"}},\"required\":[\"type\",\"data\",\"x\",\"y\"],\"additionalProperties\":false}},\"required\":[\"chart\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row-object\":{\"description\":\"Rows as objects; the columns are the union of their keys\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row-object\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-col\":{\"description\":\"Columns: column name to its values, all the same length\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"maxItems\":5000,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-col\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row\":{\"description\":\"Rows as arrays; the first row holds the column names\",\"minItems\":2,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row\"],\"additionalProperties\":false}]}}},\"required\":[\"render_all\"],\"additionalProperties\":false}]}\n```\n\nBar chart, one series per y column:\n\n```json\n{\n \"chart\": {\n \"type\": \"bar\",\n \"title\": \"Runs per day\",\n \"data\": [\n {\n \"day\": \"2026-11-10\",\n \"success\": 42,\n \"failure\": 3\n },\n {\n \"day\": \"2026-11-11\",\n \"success\": 51,\n \"failure\": 1\n }\n ],\n \"x\": \"day\",\n \"y\": [\n \"success\",\n \"failure\"\n ],\n \"stacked\": true\n }\n}\n```\n\nPie chart (exactly one y column):\n\n```json\n{\n \"chart\": {\n \"type\": \"pie\",\n \"data\": [\n {\n \"language\": \"python3\",\n \"scripts\": 18\n },\n {\n \"language\": \"bun\",\n \"scripts\": 25\n }\n ],\n \"x\": \"language\",\n \"y\": \"scripts\"\n }\n}\n```\n\nA chart and a table together:\n\n```json\n{\n \"render_all\": [\n {\n \"chart\": {\n \"type\": \"line\",\n \"data\": [\n {\n \"hour\": \"10:00\",\n \"p95_ms\": 120\n },\n {\n \"hour\": \"11:00\",\n \"p95_ms\": 180\n }\n ],\n \"x\": \"hour\",\n \"y\": \"p95_ms\",\n \"y_label\": \"ms\"\n }\n },\n {\n \"table-row-object\": [\n {\n \"hour\": \"10:00\",\n \"p95_ms\": 120,\n \"jobs\": 310\n },\n {\n \"hour\": \"11:00\",\n \"p95_ms\": 180,\n \"jobs\": 402\n }\n ]\n }\n ]\n}\n```\n", "code_mode": "# Solving a task with code\n\nWhen the user asks for something done against the systems their workspace connects to (look\nsomething up in an API, move data, check a status), answer it with a Windmill script run as a\npreview: it executes on the workspace's workers, with its resources. A script that worked can be\nsaved and run as is the next time.\n\n1. **Look for a saved script first**, by the user's words and by the system the task touches. If\n one fits, run it rather than writing new code; if one nearly fits, offer to change it rather\n than writing a near-duplicate.\n2. **Otherwise write one script and run it as a preview.** Do the fetching, filtering and\n combining in the code, and return only what answers the task, not raw API payloads. Take\n credentials as a resource-typed `main` parameter, passed as `$res:<path>` when running, never\n as a token in the code. Give `main` typed parameters for whatever would change between runs,\n so the script is reusable.\n3. **Offer to save it** when the task is likely to come back, without saving it unasked. Saving\n makes a draft, deployed only when the user asks; from then on it is an ordinary script.\n\nFor a third-party API, look up its hub integration for its resource type and how to call it.\n\n" } } diff --git a/backend/windmill-api/src/ai_session_tools/items.rs b/backend/windmill-api/src/ai_session_tools/items.rs index 7cd0c3831b..1ac49ee406 100644 --- a/backend/windmill-api/src/ai_session_tools/items.rs +++ b/backend/windmill-api/src/ai_session_tools/items.rs @@ -286,8 +286,15 @@ fn merge_config(base: Option<Value>, config: Value, path: &str) -> Map<String, V for key in ["workspace_id", "edited_by", "edited_at", "email", "error"] { draft.shift_remove(key); } + let base_identity = non_null(draft.get("permissioned_as")).cloned(); draft.extend(into_object(Some(config))); draft.insert("path".into(), json!(path)); + // As the editors do: without the flag a deploy resets the identity to the deploying user. + if base_identity.is_some() && draft.get("permissioned_as") == base_identity.as_ref() { + draft + .entry("preserve_permissioned_as") + .or_insert(json!(true)); + } draft } @@ -653,6 +660,19 @@ mod tests { (parsed, issues) } + #[test] + fn an_edit_keeps_the_identity_the_item_runs_as() { + let base = || Some(json!({"path": "p", "permissioned_as": "u/dev", "summary": "a"})); + let draft = merge_config(base(), json!({"summary": "b"}), "p"); + assert_eq!(draft["preserve_permissioned_as"], json!(true)); + + let draft = merge_config(base(), json!({"permissioned_as": "u/other"}), "p"); + assert_eq!(draft.get("preserve_permissioned_as"), None); + + let draft = merge_config(None, json!({"summary": "b"}), "p"); + assert_eq!(draft.get("preserve_permissioned_as"), None); + } + #[test] fn trigger_config_parses_like_the_session() { let kafka: Value = serde_json::from_str(&SCHEMAS.trigger["kafka"]).unwrap(); diff --git a/backend/windmill-api/src/ai_session_tools/mod.rs b/backend/windmill-api/src/ai_session_tools/mod.rs index 78b5080cb5..b7b3ebb0e8 100644 --- a/backend/windmill-api/src/ai_session_tools/mod.rs +++ b/backend/windmill-api/src/ai_session_tools/mod.rs @@ -16,7 +16,7 @@ use std::sync::LazyLock; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; -use windmill_common::auth::create_jwt_token; +use windmill_common::auth::create_jwt_token_withholding; use crate::db::ApiAuthed; @@ -477,7 +477,7 @@ impl Ctx<'_> { .get_or_try_init(|| mint_caller_jwt(self.w_id, self.auth, scopes)) .await .map_err(|e| e.to_string())?; - let mut request = crate::HTTP_CLIENT + let mut request = CALLER_HTTP_CLIENT .request(method, url) .header("Authorization", format!("Bearer {token}")) .timeout(timeout); @@ -559,6 +559,16 @@ const INSTANCE_ROUTES: &[&str] = &[ "/workspaces/users", ]; +/// Whether `w_id` has the shape of a workspace id (the `workspace.proper_id` alphabet). +/// A caller-supplied workspace is spliced into API URLs, where `/`, `.`, `?` or `%` +/// would move the call to another route. +pub(crate) fn is_plain_workspace_id(w_id: &str) -> bool { + !w_id.is_empty() + && w_id + .chars() + .all(|c| c.is_alphanumeric() || c == '-' || c == '_') +} + /// The URL of an API call, refused unless it lands on the route its handler wrote. /// /// The JWT behind a call carries the caller's full rights, and paths embed arguments a @@ -578,11 +588,8 @@ fn guarded_url( .strip_prefix("/w/") .and_then(|rest| rest.strip_prefix(w_id)) .is_some_and(|rest| rest.starts_with('/')); - let workspace_is_plain = w_id - .chars() - .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'); if path.contains('#') - || !workspace_is_plain + || !is_plain_workspace_id(w_id) || !(in_workspace || INSTANCE_ROUTES.iter().any(|r| route.starts_with(r))) { return Err(refused()); @@ -742,6 +749,23 @@ pub(super) fn matches_glob(subject: &str, glob: &str) -> bool { regex::Regex::new(&pattern).is_ok_and(|re| re.is_match(subject)) } +lazy_static::lazy_static! { + /// For requests that carry a caller JWT minted for one route: a response can be + /// shaped by a job (`wm_status_code`/`wm_headers`), and following its `Location` + /// would resend that JWT to a route the scopes were never computed for. + pub(crate) static ref CALLER_HTTP_CLIENT: reqwest::Client = + windmill_common::utils::configure_client( + reqwest::ClientBuilder::new() + .user_agent("windmill/beta") + .connect_timeout(std::time::Duration::from_secs(10)) + .timeout(std::time::Duration::from_secs(30)) + .redirect(reqwest::redirect::Policy::none()) + .danger_accept_invalid_certs(std::env::var("ACCEPT_INVALID_CERTS").is_ok()), + ) + .build() + .unwrap(); +} + /// A JWT that acts as `api_authed`, carrying `scopes`; `None` is the caller's full rights. pub(crate) async fn mint_caller_jwt( workspace_id: &str, @@ -753,7 +777,7 @@ pub(crate) async fn mint_caller_jwt( // uncapped token that satisfies require_super_admin / require_devops_role. // A browser caller stays a session: runs, trigger history and schedules attribute a // session's actions to the UI, and anything else to the API (`webhook`). - create_jwt_token( + create_jwt_token_withholding( windmill_common::db::Authed::from(api_authed.clone()), workspace_id, 3600, @@ -761,6 +785,7 @@ pub(crate) async fn mint_caller_jwt( api_authed.is_session_token.then(|| "session".to_string()), None, scopes, + (api_authed.admin_withheld, api_authed.super_admin_withheld), ) .await } @@ -783,7 +808,7 @@ pub(crate) struct ToolOutcome { /// The card tools only MCP Apps clients draw; the chat draws its own cards. #[cfg(feature = "mcp")] -pub(crate) use views::{allowed as view_allowed, definitions as view_definitions}; +pub(crate) use views::{allowed as view_allowed, definitions as view_definitions, LOAD_CARD}; pub(crate) async fn call_session_tool( ctx: &Ctx<'_>, diff --git a/backend/windmill-api/src/ai_session_tools/runs.rs b/backend/windmill-api/src/ai_session_tools/runs.rs index 3837bb7468..473443edb6 100644 --- a/backend/windmill-api/src/ai_session_tools/runs.rs +++ b/backend/windmill-api/src/ai_session_tools/runs.rs @@ -2369,14 +2369,22 @@ async fn read_run(ctx: &Ctx<'_>, args: &Value, card: bool) -> ToolResult { .filter_map(|e| e["job_id"].as_str()) .last(); let live = match running { - Some(step) => log_tail(ctx, step, 400).await.map(|(tail, _)| tail), - None => logs.map(|(tail, _)| tail), + Some(step) => log_tail(ctx, step, 400).await, + None => logs, }; - if let Some(line) = live - .as_deref() - .and_then(|l| l.lines().rev().find(|l| !l.trim().is_empty())) - { - details.insert("live_log".into(), js_head(line.trim(), 300).into()); + if let Some((tail, tail_cut)) = &live { + let lines: Vec<&str> = tail.lines().collect(); + let last = lines.iter().rposition(|l| !l.trim().is_empty()); + if let Some((i, line)) = last.map(|i| (i, lines[i])) { + // The tail's first line starts where the read did, often mid-line. + let lead = if *tail_cut && i == 0 { "…" } else { "" }; + let line = line.trim(); + let head = js_head(line, 300); + if head.len() < line.len() { + details.insert("live_log_cut".into(), true.into()); + } + details.insert("live_log".into(), format!("{lead}{head}").into()); + } } } match big_image_result(ctx, id, job, entries.first()).await { @@ -2493,11 +2501,140 @@ pub(super) async fn show_run(ctx: &Ctx<'_>, args: &Value) -> ToolResult { } } } - let status = run["status"].as_str().unwrap_or("running").to_string(); + let text = run_text(&run); ctx.set_view("windmill/run", Value::Object(run)); - Ok(format!( - "Showing run {id} ({status}) to the user as a live card." - )) + Ok(text) +} + +/// Result or log head a show tool's text carries: the rest stays in the card. +const TEXT_PREVIEW_CHARS: usize = 300; + +fn is_finished(status: &str) -> bool { + !matches!(status, "running" | "queued" | "suspended") +} + +/// "1.2 s", "3 min 05 s": a run's duration as the run page reads it. +fn duration_text(ms: f64) -> String { + match ms { + ms if ms < 1000.0 => format!("{ms:.0} ms"), + ms if ms < 120_000.0 => format!("{:.1} s", ms / 1000.0), + ms => { + let s = (ms / 1000.0).round() as u64; + format!("{} min {:02} s", s / 60, s % 60) + } + } +} + +/// What ran, from a run's card: `bash preview`, `python3 script f/x/y "Sync users"`. +fn run_kind_text(run: &Map<String, Value>) -> String { + let text = |key: &str| { + run.get(key) + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + }; + let kind = match text("job_kind").unwrap_or("job") { + "flowpreview" => "flow preview", + kind => kind, + }; + let mut out = match text("language").filter(|_| kind != "flow" && kind != "flow preview") { + Some(language) => format!("{language} {kind}"), + None => kind.to_string(), + }; + if !kind.contains("preview") { + if let Some(path) = text("path") { + out.push_str(&format!(" {path}")); + } + if let Some(summary) = text("summary") { + out.push_str(&format!(" \"{summary}\"")); + } + } + out +} + +fn run_text(run: &Map<String, Value>) -> String { + let text = |key: &str| { + run.get(key) + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + }; + let id = text("id").unwrap_or_default(); + let status = text("status").unwrap_or("running"); + let finished = is_finished(status); + let took = run + .get("duration_ms") + .and_then(Value::as_f64) + .filter(|_| finished) + .map(|ms| format!(" in {}", duration_text(ms))) + .unwrap_or_default(); + let by = text("created_by") + .map(|who| format!(", by {who}")) + .unwrap_or_default(); + let mut lines = vec![format!( + "Run {id}: {status}{took} ({}{by}).", + run_kind_text(run) + )]; + let preview = if finished { + let label = if matches!(status, "failure" | "canceled") { + "Error" + } else { + "Result" + }; + text("result").map(|r| (label, r)) + } else { + text("live_log").map(|log| ("Last log", log)) + }; + if let Some((label, value)) = preview { + let head = js_head(value, TEXT_PREVIEW_CHARS); + let flag = |key: &str| run.get(key) == Some(&Value::Bool(true)); + let cut = head.len() < value.len() + || if finished { + value != TOO_BIG_TEXT && flag("result_cut") + } else { + flag("live_log_cut") + }; + lines.push(format!("{label}: {head}{}", if cut { "…" } else { "" })); + } + if let Some(url) = text("url") { + lines.push(format!("Open: {url}")); + } + lines.push(if finished { + super::views::CARD_NOTE.to_string() + } else { + "This text is the run's state when show_run was called and does not update. Where the client draws cards, the card refreshes itself until the run finishes. To check on the run, call get_run, not show_run again.".to_string() + }); + lines.join("\n") +} + +/// A count by status, then one line per run. +fn runs_text(runs: &[Value]) -> String { + let mut counts: Vec<(&str, usize)> = Vec::new(); + for run in runs { + let status = run["status"].as_str().unwrap_or("running"); + match counts.iter_mut().find(|(s, _)| *s == status) { + Some((_, n)) => *n += 1, + None => counts.push((status, 1)), + } + } + let counts: Vec<String> = counts.iter().map(|(s, n)| format!("{n} {s}")).collect(); + let mut lines = vec![if counts.is_empty() { + "0 run(s).".to_string() + } else { + format!("{} run(s): {}.", runs.len(), counts.join(", ")) + }]; + for run in runs { + let what = run["path"] + .as_str() + .filter(|p| !p.is_empty()) + .or(run["job_kind"].as_str()) + .unwrap_or("job"); + lines.push(format!( + "- {} {what} {} {}", + run["id"].as_str().unwrap_or_default(), + run["status"].as_str().unwrap_or("running"), + run["url"].as_str().unwrap_or_default() + )); + } + lines.join("\n") } /// Runs `show_runs` draws at most: each is one job read. @@ -2540,13 +2677,14 @@ pub(super) async fn show_runs(ctx: &Ctx<'_>, args: &Value) -> ToolResult { "windmill/runs", json!({ "workspace": ctx.w_id, "runs": runs, "url": ctx.page_url("/runs") }), ); - let mut text = format!("Showing {} run(s) to the user as a table.", runs.len()); + let mut text = runs_text(&runs); if ids.len() > shown.len() { - text.push_str(&format!(" Only the first {MAX_RUNS_SHOWN} are shown.")); + text.push_str(&format!("\nOnly the first {MAX_RUNS_SHOWN} are shown.")); } if !missing.is_empty() { - text.push_str(&format!(" Not found: {}.", missing.join(", "))); + text.push_str(&format!("\nNot found: {}.", missing.join(", "))); } + text.push_str("\nShown as a table where the client draws cards."); Ok(text) } @@ -2559,6 +2697,8 @@ const CARD_ITERATIONS: usize = 10; const CARD_IMAGE_CHARS: usize = 1_000_000; /// What the job read returns in place of a result too big to send. const TOO_BIG: &str = "WINDMILL_TOO_BIG"; +/// The card's `result` for a result too large to store. +const TOO_BIG_TEXT: &str = "Too large to show here."; const CARD_STEP_RESULT_CHARS: usize = 300; const CARD_ARGS_CHARS: usize = 4000; const CARD_LOG_CHARS: i64 = 3000; @@ -2829,6 +2969,9 @@ fn run_card(id: &str, job: Option<&Value>) -> Map<String, Value> { run.insert("id".into(), id.into()); run.entry("status").or_insert("running".into()); if let Some(job) = job { + if let Some(language) = job.get("language").filter(|l| l.is_string()) { + run.insert("language".into(), language.clone()); + } let too_big = job.get("result").is_some_and(|r| r == TOO_BIG); let result = job.get("result").filter(|r| !r.is_null() && !too_big); // An agent returns its answer inside the envelope of its conversation: the card shows @@ -2845,7 +2988,7 @@ fn run_card(id: &str, job: Option<&Value>) -> Map<String, Value> { } let result = envelope.map(|e| &e["output"]).or(result); if too_big { - run.insert("result".into(), "Too large to show here.".into()); + run.insert("result".into(), TOO_BIG_TEXT.into()); run.insert("result_cut".into(), true.into()); } let error = result @@ -3051,6 +3194,49 @@ fn step_result(response: &Value, step: &str) -> String { mod tests { use super::*; + // The text is all a client that draws no card shows of a run: it must carry the outcome + // and the link, and a running run must not invite the model to poll by showing it again. + #[test] + fn show_run_text_summarizes_the_card() { + let card = |v: Value| v.as_object().unwrap().clone(); + let done = card(json!({ + "id": "01a2", "status": "success", "duration_ms": 60123, "job_kind": "preview", + "language": "bash", "created_by": "admin", "result": "done after 60 s", + "url": "https://wm.test/run/01a2?workspace=cards", "logs": "a log line", + })); + assert_eq!( + run_text(&done), + "Run 01a2: success in 60.1 s (bash preview, by admin).\n\ + Result: done after 60 s\n\ + Open: https://wm.test/run/01a2?workspace=cards\n\ + Shown as a card where the client draws cards." + ); + let failed = card(json!({ + "id": "01a3", "status": "failure", "duration_ms": 1500, "job_kind": "script", + "language": "python3", "path": "f/x/sync", "summary": "Sync users", + "result": format!("TypeError: {}", "x".repeat(400)), + })); + let text = run_text(&failed); + assert!(text.starts_with( + "Run 01a3: failure in 1.5 s (python3 script f/x/sync \"Sync users\").\nError: TypeError: xxx" + )); + assert!(text.contains("x…\n"), "{text}"); + let running = card(json!({ + "id": "01a4", "status": "running", "duration_ms": 10, "job_kind": "flow", + "path": "f/x/etl", "live_log": "step 2", "result": "stale", + })); + let text = run_text(&running); + assert!(text.starts_with("Run 01a4: running (flow f/x/etl).\nLast log: step 2\n")); + assert!( + text.ends_with( + "This text is the run's state when show_run was called and does not update. \ + Where the client draws cards, the card refreshes itself until the run finishes. \ + To check on the run, call get_run, not show_run again." + ), + "{text}" + ); + } + // The chat settles a run's arguments in the browser with `job_args.ts`, read against the // same cases by `runArgsCases.test.ts`. #[test] diff --git a/backend/windmill-api/src/ai_session_tools/views.rs b/backend/windmill-api/src/ai_session_tools/views.rs index 596d8f0630..f5a12ae351 100644 --- a/backend/windmill-api/src/ai_session_tools/views.rs +++ b/backend/windmill-api/src/ai_session_tools/views.rs @@ -9,7 +9,24 @@ use serde_json::Value; use super::{deploy, runs, workspace, Ctx, SessionAccess, ToolResult}; -pub(super) const TOOLS: &[&str] = &["show_run", "show_runs", "show_deploy_review", "show_item"]; +pub(super) const TOOLS: &[&str] = &[ + "show_run", + "show_runs", + "show_deploy_review", + "show_item", + LOAD_CARD, +]; + +/// The card's own read of what a show tool shows. Claude hands a card the result's +/// `structuredContent` but not its `_meta`, while Codex's and ChatGPT's models read +/// `structuredContent`, where a flow's card data (up to ~36k chars) would cost context on +/// every show call. So a show tool's `structuredContent` names only the call, and the card +/// loads its data through this tool, which no host lists to the model (`visibility: ["app"]`). +pub(crate) const LOAD_CARD: &str = "load_card"; + +/// The last line of each tool's text. The text is all a client that draws no card shows, and +/// all the model reads in any client: the card's data rides in `_meta`, which neither reads. +pub(super) const CARD_NOTE: &str = "Shown as a card where the client draws cards."; /// The review card's one action deploys, which only a full token may do: such a token is /// neither offered the tool nor answered when it calls it by name. @@ -18,6 +35,19 @@ pub(crate) fn allowed(name: &str, access: SessionAccess) -> bool { } pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult { + if name != LOAD_CARD { + return show(ctx, name, args).await; + } + match args.get("tool").and_then(Value::as_str) { + Some(tool) if tool != LOAD_CARD && TOOLS.contains(&tool) => { + let arguments = args.get("arguments").cloned().unwrap_or(Value::Null); + show(ctx, tool, &arguments).await + } + _ => Err(format!("{LOAD_CARD} takes the name of a show tool.")), + } +} + +async fn show(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult { if !allowed(name, ctx.access) { return Err(format!( "{name} shows drafts to deploy, and this session cannot deploy." @@ -35,11 +65,24 @@ pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult /// Each tool as `(name, description, input schema)`. All only read: the review card's /// Deploy button calls `deploy_workspace_item`, which the token's own access gates. #[cfg(feature = "mcp")] -pub(crate) fn definitions() -> [(&'static str, &'static str, Value); 4] { +pub(crate) fn definitions() -> [(&'static str, &'static str, Value); 5] { [ + ( + LOAD_CARD, + "Load the data a Windmill card shows. Only the card calls it.", + json!({ + "type": "object", + "properties": { + "tool": { "type": "string", "enum": ["show_run", "show_runs", "show_deploy_review", "show_item"] }, + "arguments": { "type": "object", "description": "The show tool's arguments, without workspace_id." } + }, + "required": ["tool", "arguments"], + "additionalProperties": false + }), + ), ( "show_run", - "Show a run to the user as a live card in the conversation: status, result, steps and logs, refreshing until it finishes, with a link to it in Windmill and a button to cancel it while it runs. Call it after starting a run the user asked for, or when they ask to see one. Do not call it for runs you start to check your own work: read those with get_run.", + "Show a run to the user as a live card in the conversation: status, result, steps and logs, refreshing until it finishes, with a link to it in Windmill and a button to cancel it while it runs. Call it after starting a run the user asked for, or when they ask to see one. Do not call it again to follow a run, and do not call it for runs you start to check your own work: read those with get_run.", json!({ "type": "object", "properties": { diff --git a/backend/windmill-api/src/ai_session_tools/workspace.rs b/backend/windmill-api/src/ai_session_tools/workspace.rs index c576ec087a..1426c5359f 100644 --- a/backend/windmill-api/src/ai_session_tools/workspace.rs +++ b/backend/windmill-api/src/ai_session_tools/workspace.rs @@ -1702,19 +1702,40 @@ pub(super) async fn show_item(ctx: &Ctx<'_>, args: &Value) -> ToolResult { }; super::deploy::deployed_page(kind, target, &Value::Null) })); + let page_url = url(page); + let kind = match (item_type, opt_str_arg(args, "trigger_kind")) { + ("trigger", Some(kind)) => format!("{kind} trigger"), + _ => item_type.to_string(), + }; + let mut text = format!("{kind} \"{path}\""); + let summary = item["summary"] + .as_str() + .or(item["value"]["summary"].as_str()); + if let Some(summary) = summary.filter(|s| !s.is_empty()) { + text.push_str(&format!(": {summary}")); + } + text.push('.'); + if let Some(page_url) = &page_url { + text.push_str(&format!("\nOpen: {page_url}")); + } + if let Some(edit_url) = edit_url.as_ref().filter(|e| Some(*e) != page_url.as_ref()) { + text.push_str(&format!("\nEdit: {edit_url}")); + } + if let Some(runs_url) = &runs_url { + text.push_str(&format!("\nWhat it runs: {runs_url}")); + } + text.push_str(&format!("\n{}", super::views::CARD_NOTE)); ctx.set_view( "windmill/item", json!({ "workspace": ctx.w_id, "item": item, - "url": url(page), + "url": page_url, "edit_url": edit_url, "runs_url": runs_url, }), ); - Ok(format!( - "Showing {item_type} \"{path}\" to the user as a card." - )) + Ok(text) } /// The editor an item's draft opens in. An app's is its own editor: its page shows only the diff --git a/backend/windmill-api/src/apps.rs b/backend/windmill-api/src/apps.rs index 3e5067c202..5cc92edd60 100644 --- a/backend/windmill-api/src/apps.rs +++ b/backend/windmill-api/src/apps.rs @@ -1604,8 +1604,8 @@ async fn mint_raw_app_sdk_token( ) -> Result<(String, chrono::DateTime<chrono::Utc>)> { // This credential outlives the request, so an ephemeral job token must not be // able to launder itself into one — the reason `users/tokens/create` refuses. - // The minted scopes do not contain it: `users/tokens/update_scopes` can widen - // any token of the same email. + // The minted scopes do not contain it: they only bound what the token reaches, + // not the identity it carries without the job's provenance. forbid_elevated_job_token(db, &authed.email, job_id).await?; // An embed token represents untrusted app JS; it must not bootstrap a // broader SDK credential (same guard as `mint_app_embed_token`). @@ -1703,6 +1703,7 @@ pub async fn build_embed_token_response( sdk_consent: bool, job_id: Option<uuid::Uuid>, ) -> Result<EmbedTokenResponse> { + let sandbox = policy.sandbox || !viewer_is_workspace_member(db, w_id, opt_authed).await?; // Only advertise scopes where a token could actually be minted, so the viewer // is never shown a permission prompt that can grant nothing: an anonymous // visitor has no identity to mint against. @@ -1742,7 +1743,7 @@ pub async fn build_embed_token_response( } _ => (None, None), } - } else if policy.sandbox { + } else if sandbox { let resp = mint_app_embed_token(db, w_id, app_path, opt_authed, job_id).await?; (resp.token, resp.expiration) } else { @@ -1756,7 +1757,7 @@ pub async fn build_embed_token_response( token, expiration, raw_app, - sandbox: policy.sandbox, + sandbox, app_path: Some(app_path.to_string()), workspace_id: Some(w_id.to_string()), sdk_scopes, @@ -1764,6 +1765,31 @@ pub async fn build_embed_token_response( }) } +/// Whether the viewer belongs to the app's workspace, the only audience for whom an +/// author's `sandbox: false` holds. Anyone else (anonymous, a guest, a superadmin of +/// another workspace) holds a session the author has no business running code with, +/// so the app renders isolated for them whatever its policy says. +async fn viewer_is_workspace_member( + db: &DB, + w_id: &str, + opt_authed: Option<&ApiAuthed>, +) -> Result<bool> { + let Some(authed) = opt_authed else { + return Ok(false); + }; + if windmill_api_auth::scopes::has_guest_sentinel(authed.scopes.as_deref()) { + return Ok(false); + } + let member: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM usr WHERE workspace_id = $1 AND email = $2 AND NOT disabled)", + ) + .bind(w_id) + .bind(&authed.email) + .fetch_one(db) + .await?; + Ok(member) +} + #[derive(Deserialize)] pub struct PreviewSdkTokenRequest { /// The app being edited. May not exist yet (a draft), so this is only used for @@ -1825,9 +1851,9 @@ pub struct EmbedTokenResponse { /// and the embed token entirely — it loads the app with the page credential. #[serde(default)] pub raw_app: bool, - /// WIN-2006: publisher opted this app into sandbox isolation. When false the - /// viewer runs the app same-origin with its full session (the default, - /// pre-isolation behavior). + /// Whether the viewer must render the app isolated: the publisher opted in, or + /// the viewer is not a member of the app's workspace. When false the viewer runs + /// the app same-origin with its full session. #[serde(default)] pub sandbox: bool, /// WIN-2006: the resolved app path. The embedder uses it (together with @@ -1877,9 +1903,9 @@ pub async fn mint_app_embed_token( job_id: Option<uuid::Uuid>, ) -> Result<EmbedTokenResponse> { let token_and_exp = if let Some(authed) = opt_authed { - // This credential outlives the request and its narrow scopes are not the - // boundary — `users/tokens/update_scopes` can widen any same-email token — - // so an elevated job token must not mint one (GHSA-hfh4-cx4h-3fcr). + // This credential outlives the request and carries the job's identity without + // the job's provenance, so an elevated job token must not mint one, whatever + // its scopes (GHSA-hfh4-cx4h-3fcr). forbid_elevated_job_token(db, &authed.email, job_id).await?; // An app embed token represents untrusted app JS in the sandboxed iframe; it // must never reach this mint path to renew itself. The 12h expiry is the @@ -1999,6 +2025,7 @@ async fn get_app_embed_token( // Resolved from the token when there is one: this endpoint serves anonymous // viewers too, so it cannot take an extractor that requires auth. OptTokened { token }: OptTokened, + windmill_common::client_ip::ClientIp(client_ip): windmill_common::client_ip::ClientIp, Extension(cache): Extension<Arc<AuthCache>>, Extension(user_db): Extension<UserDB>, Extension(db): Extension<DB>, @@ -2007,7 +2034,7 @@ async fn get_app_embed_token( ) -> JsonResult<EmbedTokenResponse> { let job_id = match token.as_deref() { Some(t) => cache - .get_opt_job_authed(Some(w_id.clone()), t) + .get_opt_job_authed(Some(w_id.clone()), t, client_ip) .await .and_then(|x| x.job_id), None => None, @@ -4795,8 +4822,9 @@ async fn execute_component( // The policy key covers only an inline script's own code, not the lock and modules // its `app_script` row runs with, so it cannot tell the deployed row from an older - // one (or from id-less code, which runs with neither). Once the deployed version has - // its lite value, a deployed row's code runs only through that row, and id-less code + // one (or from id-less code, which runs with neither). A row runs only if the deployed + // version names it, in its lite value or, until that exists, its full value. Once the + // lite value exists, a deployed row's code runs only through that row, and id-less code // only as the database studio's runtime-built queries, which have no row. Those are // limited to the languages it emits: the pin covers content, not language, and the // policy also pins frontend scripts, which must never run as e.g. bash. @@ -4821,11 +4849,13 @@ async fn execute_component( WHERE s.app = a.id AND s.code_sha256 = $4::text AND jsonb_path_exists(l.value, '$.**.inlineScript.id ? (@ == $id)', jsonb_build_object('id', s.id))) - ELSE coalesce(jsonb_path_exists(l.value, '$.**.inlineScript.id ? (@ == $id)', + ELSE coalesce(jsonb_path_exists(coalesce(l.value, v.value::jsonb), + '$.**.inlineScript.id ? (@ == $id)', jsonb_build_object('id', $3::bigint)), false) END as \"may_run!\" FROM app a LEFT JOIN app_version_lite l ON l.id = a.versions[array_upper(a.versions, 1)] + LEFT JOIN app_version v ON v.id = a.versions[array_upper(a.versions, 1)] WHERE a.path = $1 AND a.workspace_id = $2", path, &w_id, @@ -4835,10 +4865,21 @@ async fn execute_component( .fetch_optional(&db) .await?; let may_run = payload.id.is_some() || id_less_sql; - if deployed.is_some_and(|d| d.has_lite && !(may_run && d.may_run)) { - return Err(Error::NotAuthorized(format!( - "This runnable is not part of the deployed version of app {path}, reload the app" - ))); + let refused = deployed.is_some_and(|d| { + if d.has_lite { + !(may_run && d.may_run) + } else { + payload.id.is_some() && !d.may_run + } + }); + if refused { + return Err(Error::Generic( + StatusCode::CONFLICT, + format!( + "This runnable is not part of the deployed version of app {path} \ + (the app was redeployed since this page loaded). Reload the app." + ), + )); } } @@ -6117,20 +6158,27 @@ async fn check_if_allowed_to_access_s3_file_from_app( keys.iter() .any(|key| key.s3_path == file_query.s3 && key.storage == file_query.storage) }) || { + // The result is the S3 object itself or a list of them. The storage is matched with + // the key: the read goes to the requested storage as the author. sqlx::query_scalar!( r#"SELECT EXISTS ( SELECT 1 FROM v2_job_completed c JOIN v2_job j USING (id) WHERE j.workspace_id = $2 AND c.started_at > now() - interval '3 hours' - AND c.result @> ('{"s3":"' || $1 || '"}')::jsonb AND j.trigger_kind = 'app' AND j.trigger = $3 AND j.created_by = $4 + AND EXISTS ( + SELECT 1 FROM jsonb_array_elements(CASE jsonb_typeof(c.result) + WHEN 'array' THEN c.result ELSE jsonb_build_array(c.result) END) o + WHERE o->>'s3' = $1 AND o->>'storage' IS NOT DISTINCT FROM $5 + ) )"#, file_query.s3, w_id, path, creator, + file_query.storage, ) .fetch_one(db) .await? @@ -6330,6 +6378,9 @@ struct AppLoadCountQuery { search_col: Option<String>, search_term: Option<String>, storage: Option<String>, + csv_separator: Option<String>, + csv_has_header: Option<bool>, + filters: Option<String>, } #[cfg(feature = "parquet")] @@ -6342,9 +6393,9 @@ impl AppLoadCountQuery { search_term: self.search_term, storage: self.storage, s3_resource_path: None, - csv_separator: None, - csv_has_header: None, - filters: None, + csv_separator: self.csv_separator, + csv_has_header: self.csv_has_header, + filters: self.filters, }, ) } @@ -6362,6 +6413,8 @@ struct AppLoadPreviewQuery { search_term: Option<String>, storage: Option<String>, csv_separator: Option<String>, + csv_has_header: Option<bool>, + filters: Option<String>, } #[cfg(feature = "parquet")] @@ -6379,8 +6432,8 @@ impl AppLoadPreviewQuery { storage: self.storage, csv_separator: self.csv_separator, s3_resource_path: None, - csv_has_header: None, - filters: None, + csv_has_header: self.csv_has_header, + filters: self.filters, }, ) } @@ -6840,12 +6893,11 @@ async fn build_args( untrusted.insert(k, v); } } - safe_args.extend( - omit_untrusted_interpolation( - untrusted, - "The following resource has been omitted for security reasons, to allow it, toggle: 'Allow resources from users' on that field input: ", - ), - ); + safe_args.extend(omit_untrusted_interpolation( + untrusted, + "The following resource reference was not resolved; to allow it, toggle 'Allow resources \ + from users' on that field input: ", + )); for k in sensitive_inputs { let Some(v) = safe_args.get(k) else { continue }; let raw = v.get(); diff --git a/backend/windmill-api/src/apps_raw_bundler.ts b/backend/windmill-api/src/apps_raw_bundler.ts index 78bcfdf532..842fbb5475 100644 --- a/backend/windmill-api/src/apps_raw_bundler.ts +++ b/backend/windmill-api/src/apps_raw_bundler.ts @@ -53,7 +53,19 @@ export async function main( await fs.mkdir(path.dirname(abs), { recursive: true }) await fs.writeFile(abs, content) } + // bun reads `bunfig.toml` from the build directory, and some of its settings (install + // scanners, preloads, plugins) load modules from the app. The build is the deployer's job, + // and the app's files may have been written by someone else, so only the settings that say + // where packages come from are kept. + const bunfig = path.join(dir, 'bunfig.toml') for (const [p, content] of Object.entries(files ?? {})) { + if (target(p) === bunfig) { + const kept = registryOnlyBunfig(content) + if (kept !== undefined) { + await write(p, kept) + } + continue + } await write(p, content) } // `ui/` next to the app is where `wmill app bundle` looks for the shared UI. @@ -66,8 +78,13 @@ export async function main( // Piped rather than inherited so the output can go in the error too, then // echoed either way — the job's log is where someone looks to see what the // build did. + // The install and the build read the app's files (an `.npmrc` expands `${VAR}`), so they + // get the worker's environment without the job's own credentials. + const env = Object.fromEntries( + Object.entries(process.env).filter(([k]) => !k.startsWith('WM_')) + ) const spawn = (argv: string[]) => { - const proc = Bun.spawnSync(argv, { cwd: dir, stdout: 'pipe', stderr: 'pipe' }) + const proc = Bun.spawnSync(argv, { cwd: dir, env, stdout: 'pipe', stderr: 'pipe' }) const output = proc.stdout.toString() + proc.stderr.toString() console.log(output) return { ok: proc.exitCode === 0, output } @@ -80,6 +97,9 @@ export async function main( return output } + console.log( + "Dependencies are installed without lifecycle scripts, and the build runs without the job's WM_* variables." + ) if (hasPackageJson) { // Installed here rather than left to the CLI so it can be --ignore-scripts: // the app's dependencies are compiled, never run, so a package's lifecycle @@ -180,3 +200,60 @@ export async function main( const gz = (s: string) => Buffer.from(Bun.gzipSync(Buffer.from(s, 'utf8'))).toString('base64') return { js_gz: gz(js), css_gz: gz(css), triggerables_v2 } } + +/** `[install]` keys that only say where packages come from and how to resolve them. */ +const BUNFIG_INSTALL_KEYS = [ + 'registry', + 'scopes', + 'cafile', + 'ca', + 'exact', + 'optional', + 'dev', + 'peer', + 'production', + 'frozenLockfile', + 'saveTextLockfile', + 'linkWorkspacePackages' +] + +function bunfigRule(ignored: string[]): string { + const keys = BUNFIG_INSTALL_KEYS.join(', ') + const dropped = ignored.length > 0 ? `; ignored: ${ignored.join(', ')}` : '' + return `Server builds use only these [install] keys of bunfig.toml: ${keys}${dropped}. For other settings, build locally with \`wmill app bundle\`.` +} + +/** The app's bunfig reduced to the allowed `[install]` keys, or undefined if none is set. */ +function registryOnlyBunfig(content: string): string | undefined { + let parsed: any + try { + parsed = Bun.TOML.parse(content) + } catch (e) { + throw new Error(`the app's bunfig.toml is not valid TOML: ${e}`) + } + const install = parsed?.install + if (install === null || typeof install !== 'object') { + console.log(`ignoring the app's bunfig.toml: it has no [install] settings. ${bunfigRule([])}`) + return undefined + } + const lines = Object.keys(install) + .filter((k) => BUNFIG_INSTALL_KEYS.includes(k)) + .map((k) => `${JSON.stringify(k)} = ${tomlValue(install[k])}`) + const dropped = Object.keys(parsed).filter((k) => k !== 'install') + dropped.push(...Object.keys(install).filter((k) => !BUNFIG_INSTALL_KEYS.includes(k))) + if (dropped.length > 0) { + console.log(bunfigRule(dropped)) + } + return lines.length > 0 ? `[install]\n${lines.join('\n')}\n` : undefined +} + +function tomlValue(v: unknown): string { + if (typeof v === 'string') return JSON.stringify(v) + if (typeof v === 'number' || typeof v === 'boolean') return String(v) + if (Array.isArray(v)) return `[${v.map(tomlValue).join(', ')}]` + if (v !== null && typeof v === 'object') { + const entries = Object.entries(v).map(([k, x]) => `${JSON.stringify(k)} = ${tomlValue(x)}`) + return `{ ${entries.join(', ')} }` + } + throw new Error(`unsupported bunfig.toml value: ${JSON.stringify(v)}`) +} diff --git a/backend/windmill-api/src/capture.rs b/backend/windmill-api/src/capture.rs index 87d9b41714..2c6a87c0c2 100644 --- a/backend/windmill-api/src/capture.rs +++ b/backend/windmill-api/src/capture.rs @@ -364,6 +364,14 @@ async fn set_postgres_trigger_config( else { return Err(Error::BadRequest("Invalid postgres config".to_string())); }; + // The listener streams the database's changes as the saver, so this takes the scope the + // trigger and slot routes take on the same resource. + check_scopes(&authed, || { + format!( + "postgres_triggers:write:{}", + postgres_config.postgres_resource_path + ) + })?; if postgres_config.basic_mode.unwrap_or(false) { let mut pg_connection = get_default_pg_connection( @@ -578,6 +586,7 @@ async fn set_config( let config = serde_json::to_value(&nc.trigger_config)?; let new = windmill_trigger_websocket::WebsocketTrigger::config_runnables(&config); check_new_hub_paths(&new, &[], &authed, &db, &w_id).await?; + windmill_api_auth::check_run_scopes(&authed, &new)?; } let mut tx = user_db.begin(&authed).await?; @@ -1036,6 +1045,11 @@ pub async fn insert_capture_payload( preprocessor_args: PushArgsOwned, owner: &str, ) -> Result<()> { + // A capture is replayed as its tester's job, so it holds what the trigger would deliver. + let [main_args, preprocessor_args] = [main_args, preprocessor_args].map(|mut args| { + args.sanitize_untrusted(); + args.omit_untrusted_interpolation() + }); sqlx::query!( r#" INSERT INTO diff --git a/backend/windmill-api/src/concurrency_groups.rs b/backend/windmill-api/src/concurrency_groups.rs index aab73c81d9..b8017f48bf 100644 --- a/backend/windmill-api/src/concurrency_groups.rs +++ b/backend/windmill-api/src/concurrency_groups.rs @@ -1,6 +1,8 @@ use std::sync::Arc; use axum::{extract::Path, routing::get, Extension, Json, Router}; +use chrono::{DateTime, Utc}; +use serde::Serialize; use uuid::Uuid; use windmill_common::{ db::UserDB, @@ -18,6 +20,7 @@ use crate::{ pub fn global_service() -> Router { windmill_api_jobs::concurrency_groups::global_service() .route("/{job_id}/key", get(get_concurrency_key)) + .route("/{job_id}/key_status", get(get_concurrency_key_status)) } /// A concurrency key embeds the job's workspace, its runnable path and any @@ -31,15 +34,15 @@ pub fn global_service() -> Router { /// job's own workspace before evaluating access — that also rejects non-members, for whom /// the job does not exist. Members reaching [`require_job_read_access`] get its 403, which /// discloses existence only inside a workspace they belong to. -async fn get_concurrency_key( - _authed: ApiAuthed, - Tokened { token }: Tokened, - Extension(cache): Extension<Arc<AuthCache>>, - Extension(db): Extension<DB>, - Extension(user_db): Extension<UserDB>, - OptViewToken(view_token): OptViewToken, - Path(job_id): Path<Uuid>, -) -> JsonResult<Option<String>> { +async fn require_concurrency_key_read( + token: &str, + client_ip: Option<std::net::IpAddr>, + cache: &AuthCache, + db: &DB, + user_db: &UserDB, + view_token: Option<&str>, + job_id: Uuid, +) -> Result<(), Error> { let not_found = || Error::NotFound(format!("Job {job_id} not found")); // A caller who cannot reach the job must not be able to tell it apart from a job @@ -48,29 +51,91 @@ async fn get_concurrency_key( "SELECT workspace_id, created_by FROM v2_job WHERE id = $1", job_id ) - .fetch_optional(&db) + .fetch_optional(db) .await? .ok_or_else(not_found)?; let authed_in_workspace = cache - .get_authed(Some(job.workspace_id.clone()), &token) + .get_authed(Some(job.workspace_id.clone()), token, client_ip) .await .ok_or_else(not_found)?; windmill_api_auth::check_job_token_scope(&authed_in_workspace, || "jobs:read".to_string())?; require_job_read_access( - &db, - &user_db, + db, + user_db, &authed_in_workspace, &job.workspace_id, &job_id, &job.created_by, + view_token, + ) + .await +} + +async fn get_concurrency_key( + _authed: ApiAuthed, + Tokened { token }: Tokened, + windmill_common::client_ip::ClientIp(client_ip): windmill_common::client_ip::ClientIp, + Extension(cache): Extension<Arc<AuthCache>>, + Extension(db): Extension<DB>, + Extension(user_db): Extension<UserDB>, + OptViewToken(view_token): OptViewToken, + Path(job_id): Path<Uuid>, +) -> JsonResult<Option<String>> { + require_concurrency_key_read( + &token, + client_ip, + &cache, + &db, + &user_db, view_token.as_deref(), + job_id, ) .await?; - let key = sqlx::query_scalar!("SELECT key FROM concurrency_key WHERE job_id = $1", job_id) .fetch_optional(&db) .await?; Ok(Json(key)) } + +#[derive(Serialize)] +struct ConcurrencyKeyStatus { + key: String, + /// When the job was first due. Set the first time its limit held it back, and kept + /// after it ran. + deferred_from: Option<DateTime<Utc>>, + /// When the limit let the job in: the time it was last due. The rest until it started + /// is queue time. + released_at: Option<DateTime<Utc>>, +} + +async fn get_concurrency_key_status( + _authed: ApiAuthed, + Tokened { token }: Tokened, + windmill_common::client_ip::ClientIp(client_ip): windmill_common::client_ip::ClientIp, + Extension(cache): Extension<Arc<AuthCache>>, + Extension(db): Extension<DB>, + Extension(user_db): Extension<UserDB>, + OptViewToken(view_token): OptViewToken, + Path(job_id): Path<Uuid>, +) -> JsonResult<Option<ConcurrencyKeyStatus>> { + require_concurrency_key_read( + &token, + client_ip, + &cache, + &db, + &user_db, + view_token.as_deref(), + job_id, + ) + .await?; + let status = sqlx::query_as!( + ConcurrencyKeyStatus, + "SELECT key, original_scheduled_for AS deferred_from, released_at FROM concurrency_key WHERE job_id = $1", + job_id + ) + .fetch_optional(&db) + .await?; + Ok(Json(status)) +} diff --git a/backend/windmill-api/src/csrf.rs b/backend/windmill-api/src/csrf.rs index 6a8ec4a6fd..07d2dc5756 100644 --- a/backend/windmill-api/src/csrf.rs +++ b/backend/windmill-api/src/csrf.rs @@ -9,21 +9,22 @@ use axum::extract::FromRequestParts; use axum::http::{header, request::Parts, Method}; use axum::Extension; -use url::Url; +use windmill_api_auth::request_site::{self, Foreign}; use windmill_common::error::Error; use windmill_common::users::COOKIE_NAME; use crate::triggers::trigger_helpers::RunnableId; -/// Whether a request is a cross-site GET authenticating on the session cookie alone. A GET -/// handler that runs a script by path resolves it through [`Self::script_runnable`], which -/// refuses a Hub script on such a request. +/// Whether a request is a GET from a page of another origin authenticating on the session +/// cookie alone. A GET handler that runs a script by path resolves it through +/// [`Self::script_runnable`], which refuses a Hub script on such a request. /// -/// The cookie is `SameSite=Lax`, so browsers attach it to cross-site top-level GET -/// navigations. A `hub/` path runs any public Hub script, and an argument written -/// `$var:<path>` or `$res:<path>` is resolved as the caller before the script sees it: such a -/// GET lets any page pick a generic Hub script and hand it the victim's secrets, which the job -/// can then send anywhere. +/// The cookie is `SameSite=Lax`, so browsers attach it to top-level GET navigations from any +/// site, and to every request from a same-site page (a sibling subdomain). A `hub/` path runs +/// any public Hub script, and an argument written `$var:<path>` or `$res:<path>` is resolved as +/// the caller before the script sees it: such a GET lets any page pick a generic Hub script and +/// hand it the victim's secrets, which the job can then send anywhere. What counts as another +/// origin is decided by [`request_site::foreign_request`]. /// /// Workspace scripts and flows are not refused, by choice, so that GET links to them keep /// working. That is a scope decision, not a safety property: they still take attacker-chosen @@ -35,9 +36,10 @@ use crate::triggers::trigger_helpers::RunnableId; /// way to authenticate, since it cannot set headers. The checks run in `extract_token`'s /// order, header before cookie, because that is the order it resolves them in: a request /// carrying both a cookie and `token=` authenticates on the cookie and is therefore still -/// ambient, which is also why a valid `token=` link opened cross-site while signed in is -/// refused. -pub struct CrossSiteGetGuard(Option<CrossSite>); +/// ambient, which is also why a valid `token=` link opened from another site while signed in +/// is refused. Other methods never get here with the cookie: `extract_token` sets it aside on +/// a state-changing request from another origin. +pub struct CrossSiteGetGuard(Option<Foreign>); impl CrossSiteGetGuard { pub fn script_runnable( @@ -48,26 +50,14 @@ impl CrossSiteGetGuard { let (Some(signal), RunnableId::HubScript(_)) = (&self.0, &runnable_id) else { return Ok(runnable_id); }; - // The `Referer` leg is the one that can misfire, on a request that really was - // same-host: it compares against the hosts the backend can see, and a proxy that - // rewrites `Host` without setting `X-Forwarded-Host` leaves none of them matching - // what the browser addressed. Name the comparison so that shows up as a - // misconfiguration rather than as an unexplained 403. - if let CrossSite::RefererMismatch { referer, instance_hosts } = signal { - tracing::warn!( - referer_host = %referer, - ?instance_hosts, - "refusing a cross-site GET Hub script run inferred from Referer; if the request \ - was same-host, set `X-Forwarded-Host` on the proxy or configure `BASE_URL`" - ); - } - Err(Error::PermissionDenied( - "a cross-site GET request cannot run a Hub script with the session cookie, which takes \ - precedence over a `token` query parameter: pass the token in the `Authorization` \ - header, or open the link from the instance itself or from a browser with no Windmill \ - session" - .to_string(), - )) + signal.log("refusing a GET Hub script run on the session cookie"); + Err(Error::PermissionDenied(format!( + "a GET request from another site cannot run a Hub script with the session cookie, \ + which takes precedence over a `token` query parameter: pass the token in the \ + `Authorization` header, or open the link from the instance itself or from a browser \ + with no Windmill session. {}", + request_site::TRUSTED_ORIGINS_HINT + ))) } } @@ -81,7 +71,7 @@ impl<S: Send + Sync> FromRequestParts<S> for CrossSiteGetGuard { if parts.method != Method::GET { return Ok(CrossSiteGetGuard(None)); } - let Some(signal) = cross_site_signal(parts) else { + let Some(signal) = request_site::foreign_request(&parts.headers, &parts.uri) else { return Ok(CrossSiteGetGuard(None)); }; @@ -101,154 +91,3 @@ impl<S: Send + Sync> FromRequestParts<S> for CrossSiteGetGuard { Ok(CrossSiteGetGuard(has_session_cookie.then_some(signal))) } } - -enum CrossSite { - Declared, - RefererMismatch { referer: String, instance_hosts: Vec<String> }, -} - -fn cross_site_signal(parts: &Parts) -> Option<CrossSite> { - if let Some(site) = parts.headers.get("sec-fetch-site") { - return site - .as_bytes() - .eq_ignore_ascii_case(b"cross-site") - .then_some(CrossSite::Declared); - } - // Fetch Metadata rides only on potentially trustworthy URLs, so an instance served - // over plain http never receives `Sec-Fetch-Site` (nor does Safari before 16.4) while - // the cookie, not being `Secure` there either, still arrives. `Referer` is the only - // other thing a top-level GET navigation carries — `Origin` is not sent on one — so it - // is all that is left there, and it is weak: the default `strict-origin-when-cross- - // origin` policy already drops `Referer` on an https-to-http downgrade, so an https - // attacker page pointing a victim at a plain-http instance sends neither header. This - // leg catches an http-served attacker page and pre-16.4 Safari on https; the guard is - // load-bearing on https and best-effort at best on plain http. An absent `Referer` - // reads as not cross-site, matching how `Sec-Fetch-Site: none` (a bookmark, a typed - // URL) is treated. - let referer = referer_host(parts)?; - let instance_hosts: Vec<String> = instance_hosts(parts).collect(); - (!instance_hosts - .iter() - .any(|host| host.eq_ignore_ascii_case(&referer))) - .then_some(CrossSite::RefererMismatch { referer, instance_hosts }) -} - -/// Every host a legitimate same-host request can name. `Host` alone is not enough: a -/// reverse proxy that forwards without preserving it (nginx `proxy_pass` with no -/// `proxy_set_header Host $host`) hands the backend the upstream's name, which no browser -/// `Referer` will ever match. None of these is browser-settable on a navigation — a -/// navigation carries no custom headers, and `BASE_URL` is instance config — so widening -/// the accepted set costs nothing. -fn instance_hosts(parts: &Parts) -> impl Iterator<Item = String> { - let base_url = windmill_common::BASE_URL.load(); - [ - request_host(parts), - header_host(parts, "x-forwarded-host"), - Url::parse(base_url.as_str()) - .ok() - .and_then(|url| url.host_str().map(str::to_owned)), - ] - .into_iter() - .flatten() -} - -fn referer_host(parts: &Parts) -> Option<String> { - let referer = parts.headers.get(header::REFERER)?.to_str().ok()?; - Url::parse(referer).ok()?.host_str().map(str::to_owned) -} - -fn request_host(parts: &Parts) -> Option<String> { - if let Some(host) = parts.uri.host() { - return Some(host.to_owned()); - } - header_host(parts, header::HOST) -} - -fn header_host(parts: &Parts, name: impl header::AsHeaderName) -> Option<String> { - host_of(parts.headers.get(name)?.to_str().ok()?) -} - -/// The host in a `Host`-shaped header value: `host[:port]`, where `host` may be a bracketed -/// IPv6 literal, and where a chain of proxies appends to `X-Forwarded-Host` so only the -/// first entry is the one the browser addressed. The port is split off by the URL parser -/// rather than by hand-rolling the bracket rules. -fn host_of(value: &str) -> Option<String> { - let host = value.split(',').next()?.trim(); - Url::parse(&format!("http://{host}")) - .ok()? - .host_str() - .map(str::to_owned) -} - -#[cfg(test)] -mod tests { - use super::{cross_site_signal, host_of, CrossSite}; - use axum::http::{request::Parts, Request}; - - fn parts(headers: &[(&str, &str)]) -> Parts { - let mut req = Request::get("/api/w/ws/jobs/run_wait_result/p/hub/1/x"); - for (name, value) in headers { - req = req.header(*name, *value); - } - req.body(()).unwrap().into_parts().0 - } - - #[test] - fn sec_fetch_site_decides_when_present() { - let declared = |site| cross_site_signal(&parts(&[("sec-fetch-site", site)])); - assert!(matches!(declared("cross-site"), Some(CrossSite::Declared))); - for site in ["same-origin", "same-site", "none"] { - assert!(declared(site).is_none(), "{site} is not cross-site"); - } - // The header outranks a `Referer` that disagrees with it. - let with_referer = parts(&[ - ("sec-fetch-site", "same-origin"), - ("host", "windmill.example"), - ("referer", "https://attacker.example/page"), - ]); - assert!(cross_site_signal(&with_referer).is_none()); - } - - #[test] - fn referer_stands_in_when_sec_fetch_site_is_absent() { - let signal = |headers: &[(&str, &str)]| cross_site_signal(&parts(headers)); - assert!(matches!( - signal(&[ - ("host", "windmill.example"), - ("referer", "https://attacker.example/p") - ]), - Some(CrossSite::RefererMismatch { .. }) - )); - // Ports differ between the frontend and the API, and do not make a request cross-site. - assert!(signal(&[ - ("host", "windmill.example:8000"), - ("referer", "http://windmill.example:3000/apps"), - ]) - .is_none()); - // A proxy that rewrote `Host` but forwarded the public name. - assert!(signal(&[ - ("host", "windmill-server.internal"), - ("x-forwarded-host", "windmill.example"), - ("referer", "https://windmill.example/apps"), - ]) - .is_none()); - assert!(signal(&[("host", "windmill.example")]).is_none()); - } - - #[test] - fn host_of_strips_port_brackets_and_proxy_chain() { - assert_eq!(host_of("windmill.example"), Some("windmill.example".into())); - assert_eq!( - host_of("windmill.example:8000"), - Some("windmill.example".into()) - ); - assert_eq!(host_of("[::1]:8000"), Some("[::1]".into())); - assert_eq!(host_of("[::1]"), Some("[::1]".into())); - assert_eq!( - host_of("windmill.example, proxy.internal"), - Some("windmill.example".into()) - ); - assert_eq!(host_of(""), None); - assert_eq!(host_of("not a host"), None); - } -} diff --git a/backend/windmill-api/src/db.rs b/backend/windmill-api/src/db.rs index 56524011fe..c691acf608 100644 --- a/backend/windmill-api/src/db.rs +++ b/backend/windmill-api/src/db.rs @@ -126,6 +126,9 @@ lazy_static::lazy_static! { (20261106050615, include_str!( "../../migrations/20261106050615_concurrency_key_place_index.up.sql" ).replace("CREATE INDEX", "CREATE INDEX CONCURRENTLY").replace("DROP INDEX", "DROP INDEX CONCURRENTLY")), + (20261127105444, include_str!( + "../../migrations/20261127105444_token_email_index.up.sql" + ).replace("CREATE INDEX", "CREATE INDEX CONCURRENTLY").replace("DROP INDEX", "DROP INDEX CONCURRENTLY")), // The widening fails every query the previous release's still-running // servers prepared on the column; `variables::widen_variable_value` does it // once they are gone. diff --git a/backend/windmill-api/src/drafts.rs b/backend/windmill-api/src/drafts.rs index 4b0785080d..2a9bc2a28b 100644 --- a/backend/windmill-api/src/drafts.rs +++ b/backend/windmill-api/src/drafts.rs @@ -1061,6 +1061,7 @@ pub struct TransferDraftsResponse { async fn transfer_drafts( authed: ApiAuthed, tokened: crate::auth::Tokened, + windmill_common::client_ip::ClientIp(client_ip): windmill_common::client_ip::ClientIp, Extension(auth_cache): Extension<std::sync::Arc<crate::auth::AuthCache>>, Extension(db): Extension<DB>, Extension(user_db): Extension<UserDB>, @@ -1111,7 +1112,7 @@ async fn transfer_drafts( // own claims, not the database's. A job token stays refused even where its claims // list both workspaces. let authed_there = auth_cache - .get_authed(Some(target.to_string()), &tokened.token) + .get_authed(Some(target.to_string()), &tokened.token, client_ip) .await .filter(|a| a.job_id.is_none()) .ok_or_else(|| Error::PermissionDenied(format!("this token cannot act on {target}")))?; diff --git a/backend/windmill-api/src/explicit_credential.rs b/backend/windmill-api/src/explicit_credential.rs new file mode 100644 index 0000000000..13fb95df99 --- /dev/null +++ b/backend/windmill-api/src/explicit_credential.rs @@ -0,0 +1,75 @@ +/* + * 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. + */ + +use axum::http::header; +use windmill_common::error::Error; +use windmill_common::users::COOKIE_NAME; + +/// For a GET route that acts (posts a message, signs a link) rather than reads: refuses a +/// request that would authenticate on the session cookie, which a browser attaches to a +/// cross-site navigation. Its callers are jobs and scripts, which send a bearer header. +pub async fn require_explicit_credential( + req: axum::extract::Request, + next: axum::middleware::Next, +) -> axum::response::Response { + use axum::response::IntoResponse; + if authenticates_on_session_cookie(req.headers()) { + return Error::PermissionDenied( + "this route does not accept the session cookie: pass a token in the \ + `Authorization` header" + .to_string(), + ) + .into_response(); + } + next.run(req).await +} + +/// Mirrors `extract_token`: a bearer header wins, and otherwise a session cookie is used +/// before any `token` query parameter. +fn authenticates_on_session_cookie(headers: &axum::http::HeaderMap) -> bool { + let has_bearer = headers + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .is_some_and(|v| v.starts_with("Bearer ")); + !has_bearer + && headers + .get_all(header::COOKIE) + .iter() + .filter_map(|h| h.to_str().ok()) + .flat_map(|h| h.split(';')) + .filter_map(|c| tower_cookies::Cookie::parse_encoded(c.trim()).ok()) + .any(|c| c.name() == COOKIE_NAME) +} + +#[cfg(test)] +mod tests { + use super::authenticates_on_session_cookie; + use axum::http::HeaderMap; + + fn headers(pairs: &[(&'static str, &str)]) -> HeaderMap { + let mut map = HeaderMap::new(); + for (k, v) in pairs { + map.append(*k, v.parse().unwrap()); + } + map + } + + #[test] + fn session_cookie_is_refused_unless_a_bearer_header_wins() { + let cookie = + |pairs: &[(&'static str, &str)]| authenticates_on_session_cookie(&headers(pairs)); + assert!(cookie(&[("cookie", "a=b; token=abc")])); + assert!(!cookie(&[ + ("cookie", "token=abc"), + ("authorization", "Bearer xyz") + ])); + assert!(!cookie(&[("cookie", "other=abc")])); + assert!(!cookie(&[("authorization", "Bearer xyz")])); + assert!(!cookie(&[])); + } +} diff --git a/backend/windmill-api/src/jobs.rs b/backend/windmill-api/src/jobs.rs index fd13006181..5b99c044a1 100644 --- a/backend/windmill-api/src/jobs.rs +++ b/backend/windmill-api/src/jobs.rs @@ -291,7 +291,10 @@ pub fn workspaced_service() -> Router { ) .route("/add_batch_jobs/{n}", post(add_batch_jobs)) .route("/run/preview_flow", post(run_preview_flow_job)) - .route("/run/flow_test/{*path}", post(crate::flow_test::run_flow_test)) + .route( + "/run/flow_test/{*path}", + post(crate::flow_test::run_flow_test), + ) .route("/run/agent/{*path}", post(crate::agent_runs::run_agent)) .route( "/run_wait_result/preview_flow", @@ -409,6 +412,11 @@ pub fn workspaced_service() -> Router { "/flow/approval_step_detail/{job_id}/{step_id}", get(get_approval_step_detail), ) + .route( + "/flow/nested_approvals/{job_id}", + get(list_nested_approvals), + ) + .route("/approvals/waiting", get(list_waiting_approvals)) .route( "/job_view_token/{id}", get(get_job_view_token).layer(cors.clone()), @@ -471,6 +479,10 @@ pub fn workspace_unauthed_service() -> Router { .route("/get_flow_debug_info/{id}", get(get_flow_job_debug_info)) .route("/completed/get/{id}", get(get_completed_job)) .route("/completed/get_result/{id}", get(get_completed_job_result)) + .route( + "/completed/get_result_shape/{id}", + get(get_completed_job_result_shape), + ) .route( "/completed/get_result_maybe/{id}", get(get_completed_job_result_maybe), @@ -5348,6 +5360,8 @@ struct ApprovalInfo { step_summary: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] flow_summary: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + required_events: Option<u32>, approvers: Vec<Approval>, /// Share-read-link token for the flow, minted only for callers allowed to view this /// approval. Lets an authenticated workspace-member approver open the run details of @@ -5441,6 +5455,10 @@ fn approval_conditions_from_settings(suspend: &Suspend) -> Option<ApprovalCondit struct ApprovalStepView { skin: ApprovalSkin, summary: Option<String>, + required_events: Option<u32>, + /// The approval step's job: approvals sent to it count for this step, with those sent to + /// the flow itself. Rows for the flow's earlier steps stay until the run finishes. + job: Option<Uuid>, } async fn get_approval_info( @@ -5529,7 +5547,8 @@ async fn get_approval_info( .and_then(|m| m.get("skin")) .and_then(|v| serde_json::from_value::<ApprovalSkin>(v.clone()).ok()) .unwrap_or_default(); - let step = Some(ApprovalStepView { skin, summary: None }); + let step = + Some(ApprovalStepView { skin, summary: None, required_events: None, job: None }); (form, description, default_args, enums, run_ac, None, step) } else { let fs = row @@ -5609,6 +5628,10 @@ async fn get_approval_info( .and_then(|module| module.suspend.as_ref()) .and_then(approval_conditions_from_settings) }); + let step_job_id = fs + .as_ref() + .and_then(|s| approval_step.and_then(|step| s.modules.get(step))) + .and_then(|m| m.job()); let step = approval_module.map(|module| ApprovalStepView { skin: module .suspend @@ -5616,13 +5639,11 @@ async fn get_approval_info( .and_then(|s| s.skin) .unwrap_or_default(), summary: module.summary.clone().filter(|s| !s.trim().is_empty()), + required_events: module.suspend.as_ref().and_then(|s| s.required_events), + job: step_job_id, }); // Fetch description, default_args, and enums from the step's completed job result - let step_job_id = fs - .as_ref() - .and_then(|s| approval_step.and_then(|step| s.modules.get(step))) - .and_then(|m| m.job()); let (desc, default_args, enums) = if let Some(sjid) = step_job_id { let result: Option<serde_json::Value> = sqlx::query_scalar( "SELECT result FROM v2_job_completed WHERE id = $1 AND workspace_id = $2", @@ -5644,6 +5665,8 @@ async fn get_approval_info( }; let skin = step.as_ref().map(|s| s.skin).unwrap_or_default(); + let required_events = step.as_ref().and_then(|s| s.required_events); + let step_job = step.as_ref().and_then(|s| s.job); let step_summary = step.and_then(|s| s.summary); let user_auth_required = approval_conditions @@ -5678,22 +5701,27 @@ async fn get_approval_info( skin, step_summary: None, flow_summary: None, + required_events: None, approvers: vec![], view_token: None, })); } // Get existing approvers - let approvers: Vec<Approval> = sqlx::query_as::<_, (i32, Option<String>)>( - "SELECT resume_id, approver FROM resume_job WHERE flow = $1", + let approvers: Vec<Approval> = sqlx::query!( + "SELECT resume_id, approver, created_at, approved FROM resume_job + WHERE flow = $1 AND ($2::uuid IS NULL OR job IN ($1, $2))", + job_id, + step_job ) - .bind(&job_id) .fetch_all(&db) .await? .into_iter() - .map(|(rid, approver)| Approval { - resume_id: rid as u16, - approver: approver.unwrap_or_else(|| "anonymous".to_string()), + .map(|r| Approval { + resume_id: r.resume_id as u16, + approver: r.approver.unwrap_or_else(|| "anonymous".to_string()), + approved_at: Some(r.created_at), + approved: Some(r.approved), }) .collect(); @@ -5725,6 +5753,7 @@ async fn get_approval_info( skin, step_summary, flow_summary: row.flow_summary, + required_events, approvers, view_token, })) @@ -5744,11 +5773,377 @@ enum ApprovalStepStatus { NotResumed, } +#[derive(Serialize)] +struct WaitingApproval { + /// The suspended flow, the one its approval page takes: the root run, or the branch, loop or + /// subflow run holding the step. + job_id: Uuid, + #[serde(skip_serializing_if = "Option::is_none")] + flow_path: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + flow_summary: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + step_summary: Option<String>, + started_by: String, + created_at: chrono::DateTime<chrono::Utc>, + approvals: i64, + required_approvals: i64, +} + +#[derive(Serialize)] +struct WaitingApprovals { + approvals: Vec<WaitingApproval>, + /// Every listed run, of which `approvals` holds the most recent. + total: usize, +} + +// ponytail: scans the most recent suspended runs only; a workspace past this many waiting +// approvals needs the approver check in SQL rather than in `can_approve_step`. +const WAITING_APPROVALS_SCAN: i64 = 1000; +const WAITING_APPROVALS_RETURNED: usize = 100; + +#[derive(Serialize)] +struct NestedApproval { + job_id: Uuid, + subflows: Vec<String>, + step_id: String, + step_summary: Option<String>, + /// Fewer approvers than this on a step that went past: it timed out and continued. + required_events: u64, + approvers: Vec<Approval>, +} + +#[derive(Serialize)] +struct NestedApprovals { + approvals: Vec<NestedApproval>, + more: bool, +} + +/// Whether a step can start a run holding an approval step: a subflow, whose steps its caller +/// does not carry, or a loop or branch whose own steps hold one. +fn may_hold_approval(step: &serde_json::Value) -> bool { + let holds = |modules: &serde_json::Value| { + modules + .as_array() + .into_iter() + .flatten() + .any(|m| m.get("suspend").is_some_and(|s| !s.is_null()) || may_hold_approval(m)) + }; + let branches = |v: &serde_json::Value| { + v["branches"] + .as_array() + .into_iter() + .flatten() + .any(|b| holds(&b["modules"])) + }; + let v = &step["value"]; + match v["type"].as_str() { + Some("flow") => true, + Some("forloopflow" | "whileloopflow") => holds(&v["modules"]), + Some("branchone") => holds(&v["default"]) || branches(v), + Some("branchall") => branches(v), + _ => false, + } +} + +/// The ids of the steps under `modules`, at any depth, that may hold an approval. Read from a +/// flow's full definition: a loop or branch run's own (`flow_node`) keeps nested loop and branch +/// bodies as `modules_node` references, so its inline steps are not all of them. Step ids are +/// unique across a flow, so its loop and branch runs look their steps up here. +fn approval_holders(modules: &[serde_json::Value], out: &mut HashSet<String>) { + for m in modules { + if may_hold_approval(m) { + if let Some(id) = m["id"].as_str() { + out.insert(id.to_string()); + } + } + let v = &m["value"]; + let nested = std::iter::once(&v["modules"]) + .chain(std::iter::once(&v["default"])) + .chain(v["branches"].as_array().into_iter().flatten().map(|b| &b["modules"])); + for body in nested { + approval_holders(body.as_array().map(Vec::as_slice).unwrap_or_default(), out); + } + } +} + +// ponytail: a loop whose steps hold an approval has one per iteration; past this many nested +// runs read, the rest stay on their own runs' pages. +const NESTED_RUNS_READ: usize = 200; + +/// The approval steps that runs nested under a flow run (subflows, branch and loop runs, at any +/// depth) went past. Who approved them is kept on those runs, not on the flow run. Only the +/// runs started by a step that can hold an approval step are read, one level at a time. +async fn list_nested_approvals( + OptViewToken(view_token): OptViewToken, + authed: ApiAuthed, + Extension(db): Extension<DB>, + Extension(user_db): Extension<UserDB>, + Path((w_id, flow_id)): Path<(String, Uuid)>, +) -> error::Result<Json<NestedApprovals>> { + let created_by = sqlx::query_scalar!( + "SELECT created_by FROM v2_job WHERE id = $1 AND workspace_id = $2", + flow_id, + w_id + ) + .fetch_optional(&db) + .await? + .ok_or_else(|| Error::NotFound(format!("Job {flow_id} not found")))?; + require_job_read_access( + &db, + &user_db, + &authed, + &w_id, + &flow_id, + &created_by, + view_token.as_deref(), + ) + .await?; + + let modules = |v: &Option<serde_json::Value>| -> Vec<serde_json::Value> { + v.as_ref() + .and_then(|v| v.get("modules")) + .and_then(|m| m.as_array()) + .cloned() + .unwrap_or_default() + }; + let scope_tags = get_scope_tags(&authed); + // Each run to read, with the subflow steps leading to it (none for the flow run itself) and, + // for a loop or branch run, the steps of its flow that may hold an approval. + type Holders = std::sync::Arc<HashSet<String>>; + let mut level: HashMap<Uuid, (Option<Vec<String>>, Option<Holders>)> = + HashMap::from([(flow_id, (None, None))]); + let mut seen: HashSet<Uuid> = HashSet::from([flow_id]); + let mut approvals = vec![]; + let mut more = false; + while !level.is_empty() { + let ids: Vec<Uuid> = level.keys().copied().collect(); + let rows = sqlx::query!( + r#"SELECT j.id, j.tag, j.kind = 'flownode' AS "is_node!", + COALESCE(s.flow_status, c.flow_status) AS flow_status, + COALESCE(j.raw_flow, fv.value, fn.flow) AS flow + FROM v2_job j + LEFT JOIN v2_job_status s ON s.id = j.id + LEFT JOIN v2_job_completed c ON c.id = j.id + LEFT JOIN flow_version fv + ON j.raw_flow IS NULL AND j.kind = 'flow' AND fv.id = j.runnable_id + LEFT JOIN flow_node fn + ON j.raw_flow IS NULL AND j.kind = 'flownode' AND fn.id = j.runnable_id + WHERE j.id = ANY($1) AND j.workspace_id = $2"#, + &ids, + w_id + ) + .fetch_all(&db) + .await?; + let mut next = HashMap::new(); + for r in rows { + let (at, inherited) = level.get(&r.id).cloned().unwrap_or_default(); + let defs = modules(&r.flow); + let holders = match inherited { + Some(h) if r.is_node => h, + _ => { + let mut h = HashSet::new(); + approval_holders(&defs, &mut h); + std::sync::Arc::new(h) + } + }; + let statuses = modules(&r.flow_status); + // The read check admitted the flow run on its own tag only. A nested run outside + // the caller's tag scope is still walked through, so it cannot hide a descendant + // the caller could read directly, but its approvals are not returned. + let in_scope = scope_tags.as_ref().map_or(true, |t| t.contains(&r.tag.as_str())); + if let (Some(subflows), true) = (&at, in_scope) { + let flow_step = r.flow_status.as_ref().and_then(|f| f["step"].as_u64()); + for (i, m) in statuses.iter().enumerate() { + // A step `skip_if` skipped never asked for approval. + if m["type"] != "Success" || m["skipped"].as_bool() == Some(true) { + continue; + } + let step_id = m["id"].as_str().unwrap_or_default(); + let def = defs.iter().find(|d| d["id"] == step_id); + if !def.is_some_and(|d| !d["suspend"].is_null()) { + continue; + } + let approvers: Vec<Approval> = + serde_json::from_value(m["approvers"].clone()).unwrap_or_default(); + // No response and the flow moved past the step after it: it timed out and + // continued. While it waits, `step` is that next step's index. + if approvers.is_empty() && !flow_step.is_some_and(|s| s > i as u64 + 1) { + continue; + } + let step_summary = def + .and_then(|d| d["summary"].as_str()) + .filter(|s| !s.is_empty()) + .map(str::to_string); + let required_events = def + .and_then(|d| d["suspend"]["required_events"].as_u64()) + .unwrap_or(1); + approvals.push(NestedApproval { + job_id: r.id, + subflows: subflows.clone(), + step_id: step_id.to_string(), + step_summary, + required_events, + approvers, + }); + } + } + for d in &defs { + let Some(step) = d["id"].as_str().filter(|s| holders.contains(*s)) else { + continue; + }; + let Some(status) = statuses.iter().find(|s| s["id"] == step) else { + continue; + }; + let mut subflows = at.clone().unwrap_or_default(); + if d["value"]["type"] == "flow" { + subflows.push(step.to_string()); + } + // A subflow or branch run is the step's `job`, a loop's or a branch's runs its + // `flow_jobs`. + let started = std::iter::once(&status["job"]) + .chain(status["flow_jobs"].as_array().into_iter().flatten()) + .filter_map(|v| v.as_str()?.parse::<Uuid>().ok()); + for child in started { + if seen.len() > NESTED_RUNS_READ { + more = true; + break; + } + if seen.insert(child) { + next.insert(child, (Some(subflows.clone()), Some(holders.clone()))); + } + } + } + } + level = next; + } + approvals.sort_by_key(|a| a.approvers.first().and_then(|a| a.approved_at)); + Ok(Json(NestedApprovals { approvals, more })) +} + +/// The runs waiting on an approval step set to show on Home that the caller can approve, by the +/// same check the resume boundary runs. A step anyone holding its link can approve is listed +/// only to those who can read its run, or every member would learn the names of flows they +/// have no access to. +async fn list_waiting_approvals( + authed: ApiAuthed, + Extension(db): Extension<DB>, + Extension(user_db): Extension<UserDB>, + Path(w_id): Path<String>, +) -> error::Result<Json<WaitingApprovals>> { + // A token confined to some tags reads no job outside them, here as in every job read. + let scope_tags = + get_scope_tags(&authed).map(|v| v.into_iter().map(str::to_string).collect::<Vec<_>>()); + let rows = sqlx::query!( + r#" + SELECT j.id AS "id!", + COALESCE(j.root_job, j.parent_job, j.id) AS "root_job_id!", + j.runnable_path, + j.permissioned_as_email AS "email!", + j.created_by AS "created_by!", + j.created_at AS "created_at!", + COALESCE(rj.runnable_path, j.runnable_path) AS flow_path, + NULLIF(f.summary, '') AS flow_summary, + s.flow_status->'approval_conditions' AS approval_conditions, + NULLIF(w.m->'home'->>'step_summary', '') AS step_summary, + COALESCE((w.m->>'count')::bigint, 1) AS "required_approvals!", + -- Counted as the worker counts them: those sent to the approval step's job, + -- plus those sent to the flow itself. + (SELECT count(*) FROM resume_job r WHERE r.job IN (j.id, (w.m->>'job')::uuid)) + AS "approvals!", + EXISTS(SELECT 1 FROM resume_job r + WHERE r.job IN (j.id, (w.m->>'job')::uuid) AND r.approver = $2) + AS "approved_by_me!" + FROM v2_job_queue q + JOIN v2_job j ON j.id = q.id + JOIN v2_job_status s ON s.id = q.id + LEFT JOIN v2_job rj ON rj.id = COALESCE(j.root_job, j.parent_job) + LEFT JOIN flow f + ON f.workspace_id = j.workspace_id + AND f.path = COALESCE(rj.runnable_path, j.runnable_path) + -- The step waiting on the approval, which the worker marks `home` when the approval + -- step has `show_on_home`: only those are listed, since many approvals are announced + -- elsewhere (a resume link sent to a chat) and every admin and owner could give them. + CROSS JOIN LATERAL ( + SELECT s.flow_status->'modules'->((s.flow_status->>'step')::int) AS m + ) w + WHERE q.workspace_id = $1 + AND q.suspend > 0 + AND w.m->>'type' = 'WaitingForEvents' + AND w.m->'home' IS NOT NULL + AND ($4::text[] IS NULL OR j.tag = ANY($4)) + ORDER BY j.created_at DESC + LIMIT $3 + "#, + &w_id, + &authed.username, + WAITING_APPROVALS_SCAN, + scope_tags.as_deref(), + ) + .fetch_all(&db) + .await?; + + let candidates: Vec<_> = rows + .into_iter() + .filter(|r| !r.approved_by_me) + .filter_map(|r| { + let ac = r + .approval_conditions + .as_ref() + .and_then(|v| serde_json::from_value::<ApprovalConditions>(v.clone()).ok()); + let opt_authed = Some(authed.clone()); + can_approve_step(&opt_authed, &ac, r.runnable_path.as_deref(), &r.email).then(|| { + let auth_required = ac.as_ref().is_some_and(|ac| ac.user_auth_required); + (r, auth_required) + }) + }) + .collect(); + + let root_ids: Vec<Uuid> = candidates + .iter() + .filter(|(_, auth_required)| !auth_required) + .map(|(r, _)| r.root_job_id) + .collect(); + let readable: std::collections::HashSet<Uuid> = if root_ids.is_empty() { + Default::default() + } else { + let mut tx = user_db.begin(&authed).await?; + let ids = sqlx::query_scalar!("SELECT id FROM v2_job WHERE id = ANY($1)", &root_ids) + .fetch_all(&mut *tx) + .await?; + tx.commit().await?; + ids.into_iter().collect() + }; + + let listed: Vec<WaitingApproval> = candidates + .into_iter() + .filter_map(|(r, auth_required)| { + (auth_required || readable.contains(&r.root_job_id)).then(|| WaitingApproval { + job_id: r.id, + flow_path: r.flow_path, + flow_summary: r.flow_summary, + step_summary: r.step_summary, + started_by: r.created_by, + created_at: r.created_at, + approvals: r.approvals, + required_approvals: r.required_approvals, + }) + }) + .collect(); + let total = listed.len(); + let approvals = listed + .into_iter() + .take(WAITING_APPROVALS_RETURNED) + .collect(); + Ok(Json(WaitingApprovals { approvals, total })) +} + #[derive(Serialize)] struct StepApproval { resume_id: u16, approver: String, - /// Known only while the run is live: a finished run keeps approver names alone. + /// Known only while the run is live, as is `value`: a finished run keeps approver names and + /// times alone. #[serde(skip_serializing_if = "Option::is_none")] approved: Option<bool>, #[serde(skip_serializing_if = "Option::is_none")] @@ -5861,7 +6256,6 @@ async fn get_approval_step_detail( module: Option<serde_json::Value>, next_module: Option<serde_json::Value>, module_def: Option<serde_json::Value>, - is_last_module: bool, run_approval_conditions: Option<serde_json::Value>, suspend_until: Option<chrono::DateTime<chrono::Utc>>, flow_error: Option<serde_json::Value>, @@ -5880,10 +6274,6 @@ async fn get_approval_step_detail( '$.modules[*] ? (@.id == $id)', jsonb_build_object('id', $3::text) ) AS module_def, - COALESCE( - COALESCE(j.raw_flow, fv.value, fn.flow)->'modules'->-1->>'id' = $3, - false - ) AS is_last_module, s.flow_status->'approval_conditions' AS run_approval_conditions, q.suspend_until, c.result->'error' AS flow_error, @@ -5947,12 +6337,13 @@ async fn get_approval_step_detail( .module_def .and_then(|v| serde_json::from_value(v).ok()) .ok_or_else(not_found)?; - // The worker holds a run only after a step with a positive `required_events` that has a - // step after it (`needs_resume`); the last step's suspend settings never stop the run. + // The worker holds a run only after a step with a positive `required_events`. A last step + // holds it too: the worker appends a virtual step after it (`add_virtual_items_if_necessary`), + // which the stored flow does not carry. let suspend = module_def .suspend .as_ref() - .filter(|s| s.required_events.unwrap_or(0) > 0 && !row.is_last_module) + .filter(|s| s.required_events.unwrap_or(0) > 0) .ok_or_else(|| { Error::BadRequest(format!("Step {step_id} is not an approval (suspend) step")) })?; @@ -5999,9 +6390,9 @@ async fn get_approval_step_detail( .map(|a| StepApproval { resume_id: a.resume_id, approver: a.approver.clone(), - approved: None, + approved: a.approved, value: None, - created_at: None, + created_at: a.approved_at, }) .collect() } else { @@ -6312,10 +6703,17 @@ async fn insert_resume_job<'c>( approved: bool, tx: &mut Transaction<'c, Postgres>, ) -> error::Result<()> { - // The approver, possibly anonymous, writes this payload, and later steps receive it as - // `resume`, interpolated with the flow's own token. - if windmill_common::variables::untrusted_arg_interpolates(&value.to_string()) { - let what = if approved { + // The approver, possibly anonymous, writes this payload and the approver name, and later + // steps receive them as `resume` and `approvers`, interpolated with the flow's own token. + let approver_interpolates = approver.as_ref().is_some_and(|a| { + windmill_common::variables::untrusted_arg_interpolates(&serde_json::json!(a).to_string()) + }); + if approver_interpolates + || windmill_common::variables::untrusted_arg_interpolates(&value.to_string()) + { + let what = if approver_interpolates { + "The approver name" + } else if approved { "The resume payload" } else { "The denial reason" @@ -6594,6 +6992,8 @@ pub async fn get_suspended_job_flow( .map(|x| Approval { resume_id: x.resume_id as u16, approver: x.approver.unwrap_or_else(|| "anonymous".to_string()), + approved_at: None, + approved: None, }) .collect() } else { @@ -7441,6 +7841,7 @@ async fn batch_rerun_handle_job( .and_then(serde_json::Value::as_object) .and_then(|s| s.get("properties")) .and_then(serde_json::Value::as_object); + let mut replaced = std::collections::HashSet::new(); for (property_name, transform) in input_transforms { let schema_has_key = schema .map(|s| s.contains_key(property_name)) @@ -7451,17 +7852,37 @@ async fn batch_rerun_handle_job( match transform { InputTransform::Static { value } => { args.insert(property_name.clone(), value.clone()); + replaced.insert(property_name); } InputTransform::Javascript { expr } => { args.insert( property_name.clone(), batch_rerun_compute_js_expression(expr.clone(), job.clone()).await?, ); + replaced.insert(property_name); } InputTransform::Ai => {} } } + // The re-run resolves its args with the caller's token, so references written by whoever + // started the source job must not carry over. + if job.created_by != authed.username { + if let Some(name) = args.iter().find_map(|(k, v)| { + (!replaced.contains(k) + && windmill_common::variables::untrusted_arg_interpolates(v.get())) + .then_some(k) + }) { + return Err(Error::BadRequest(format!( + "Job {} was started by {}: its argument `{name}` holds $var:, $jsonvar:, $res: \ + or $encrypted: references or a $WM_* variable name, which a re-run by another \ + user cannot carry over. Ask {} to re-run it, or re-run it from the run form \ + with the argument filled in.", + job.id, job.created_by, job.created_by + ))); + } + } + // Call appropriate function to push job to queue match job.kind { JobKind::Flow => { @@ -8328,15 +8749,20 @@ pub async fn run_workflow_as_code( run_query.timeout, None, ), + // The version the parent runs, not the path's latest: the parent's identity was + // granted to that version's code. JobKind::Script => { + let hash = job.script_hash.ok_or_else(|| { + error::Error::BadRequest(format!("job {job_id} runs no script version")) + })?; let userdb_authed = UserDbWithAuthed { db: user_db.clone(), authed: &authed.to_authed_ref() }; - let script = RunnableRef::from_path(job.script_path(), false)?; - script_path_to_payload( - &script, - RunOrigin::Deployed, - Some(userdb_authed), - db.clone(), + let script_info = + get_script_info_for_hash(Some(userdb_authed), &db, &w_id, hash.0).await?; + windmill_common::jobs::script_info_to_payload( + script_info, + job.script_path(), + &db, &w_id, run_query.skip_preprocessor, ) @@ -9652,8 +10078,18 @@ async fn run_preview_script( ) -> error::Result<(StatusCode, String)> { #[cfg(feature = "enterprise")] check_license_key_valid().await?; - // A deferred run would outlive the running job the exemption keys off. + // A deferred run would outlive the running job the exemption keys off. The other fields + // choose code other than `content` (a deployed script, its modules, a dedicated worker), + // which the exemption's checks never see. let datatable_query = run_query.get_scheduled_for(&db).await?.is_none() + && matches!(preview.kind, None | Some(PreviewKind::Code)) + && preview.script_hash.is_none() + && preview.path.is_none() + && preview.lock.is_none() + && preview.modules.is_none() + && preview.temp_script_refs.is_none() + && preview.flow_path.is_none() + && preview.dedicated_worker.is_none() && operator_may_run_datatable_query( &db, &w_id, @@ -10562,6 +10998,7 @@ async fn add_batch_jobs( Json(batch_info): Json<BatchInfo>, ) -> error::JsonResult<Vec<Uuid>> { require_super_admin(&db, &authed).await?; + check_scopes(&authed, || "jobs:run".to_string())?; let mut job_token_scopes: Option<Vec<String>> = None; let ( @@ -10998,7 +11435,8 @@ pub(crate) async fn push_preview_flow_job( "UPDATE v2_job_status SET flow_status = jsonb_set(flow_status, '{test_subflows}', $2) WHERE id = $1", uuid, - sqlx::types::Json(test_subflows) as sqlx::types::Json<HashMap<String, serde_json::Value>> + sqlx::types::Json(test_subflows) + as sqlx::types::Json<HashMap<String, serde_json::Value>> ) .execute(&mut *tx) .await?; @@ -12637,6 +13075,127 @@ async fn get_completed_job_result( Ok(Json(raw_result.result).into_response()) } +/// Elements listed by `get_result_shape`; the rest of a longer list is counted only. +const RESULT_SHAPE_MAX_ITEMS: i64 = 100; +/// Keys listed per object by `get_result_shape`. +const RESULT_SHAPE_MAX_KEYS: i64 = 20; + +#[derive(Deserialize)] +struct ResultShapeQuery { + json_path: Option<String>, +} + +#[derive(Serialize, Deserialize, Debug)] +struct ResultShapeItem { + length: i32, + #[serde(skip_serializing_if = "Option::is_none")] + keys: Option<Vec<String>>, +} + +#[derive(Serialize)] +struct ResultShape { + #[serde(rename = "type")] + type_: String, + length: i32, + #[serde(skip_serializing_if = "Option::is_none")] + keys: Option<Vec<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + item_count: Option<i32>, + #[serde(skip_serializing_if = "Option::is_none")] + items: Option<Vec<ResultShapeItem>>, +} + +/// The outline of a result too large to send inline: its JSON length, its keys, and the same +/// for each element of a list, so a viewer can offer each part without reading the whole. +async fn get_completed_job_result_shape( + OptViewToken(view_token): OptViewToken, + OptAuthed(opt_authed): OptAuthed, + opt_tokened: OptTokened, + Extension(db): Extension<DB>, + Extension(user_db): Extension<UserDB>, + Path((w_id, id)): Path<(String, Uuid)>, + Query(ResultShapeQuery { json_path }): Query<ResultShapeQuery>, +) -> JsonResult<ResultShape> { + let tags = opt_authed + .as_ref() + .map(|authed| get_scope_tags(authed)) + .flatten(); + let path: Vec<&str> = json_path + .as_deref() + .filter(|p| !p.is_empty()) + .map(|p| p.split('.').collect()) + .unwrap_or_default(); + let row = sqlx::query!( + r#"WITH v AS ( + SELECT c.result #> $3 AS r, created_by + FROM v2_job_completed c JOIN v2_job USING (id) + WHERE c.id = $1 AND c.workspace_id = $2 AND ($4::text[] IS NULL OR tag = ANY($4)) + ) + SELECT + created_by AS "created_by!", + jsonb_typeof(r) AS "type", + length(r::text) AS "length", + CASE WHEN jsonb_typeof(r) = 'object' THEN + ARRAY(SELECT jsonb_object_keys(r) LIMIT $6) + END AS "keys", + CASE WHEN jsonb_typeof(r) = 'array' THEN jsonb_array_length(r) END AS "item_count", + CASE WHEN jsonb_typeof(r) = 'array' THEN ( + SELECT jsonb_agg(jsonb_build_object( + 'length', length(e::text), + 'keys', CASE WHEN jsonb_typeof(e) = 'object' THEN + to_jsonb(ARRAY(SELECT jsonb_object_keys(e) LIMIT $6)) + END + ) ORDER BY i) + FROM jsonb_array_elements(r) WITH ORDINALITY AS t(e, i) + WHERE i <= $5 + ) END AS "items: sqlx::types::Json<Vec<ResultShapeItem>>" + FROM v"#, + id, + &w_id, + &path as &[&str], + tags.as_ref().map(|v| v.as_slice()) as Option<&[&str]>, + RESULT_SHAPE_MAX_ITEMS, + RESULT_SHAPE_MAX_KEYS, + ) + .fetch_optional(&db) + .await?; + let row = not_found_if_none(row, "Completed Job", id.to_string())?; + + require_opt_authed_job_read_access( + &db, + &user_db, + &opt_authed, + &w_id, + &id, + &row.created_by, + view_token.as_deref(), + ) + .await?; + + let Some(type_) = row.r#type else { + return Err(Error::NotFound(format!( + "no value at {} in the result of job {id}", + json_path.unwrap_or_default() + ))); + }; + log_job_view( + &db, + opt_authed.as_ref(), + opt_tokened.token.as_deref(), + &w_id, + &id, + ) + .await?; + + Ok(Json(ResultShape { + type_, + length: row.length.unwrap_or(0), + keys: row.keys, + item_count: row.item_count, + items: row.items.map(|items| items.0), + })) +} + #[derive(Deserialize)] struct CountByTagQuery { horizon_secs: Option<i64>, @@ -13476,6 +14035,9 @@ mod approval_view_gate_tests { credential_expiry: None, mcp_client: None, capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), + allowed_ips: None, + admin_withheld: false, + super_admin_withheld: false, } } @@ -13625,3 +14187,84 @@ mod approval_view_gate_tests { assert!(from_settings(serde_json::json!({})).is_none()); } } + +#[cfg(test)] +mod nested_approvals_tests { + use super::{approval_holders, may_hold_approval}; + use serde_json::json; + + fn script(id: &str) -> serde_json::Value { + json!({"id": id, "value": {"type": "rawscript", "content": "", "language": "bun"}}) + } + + fn approval(id: &str) -> serde_json::Value { + let mut s = script(id); + s["suspend"] = json!({"required_events": 1}); + s + } + + #[test] + fn reads_only_steps_that_can_hold_an_approval() { + // A subflow's steps are not in its caller's definition: always followed. + assert!(may_hold_approval( + &json!({"id": "sub", "value": {"type": "flow", "path": "f/a/b"}}) + )); + let lp = |modules| json!({"id": "l", "value": {"type": "forloopflow", "modules": modules}}); + assert!(!may_hold_approval(&lp(json!([script("a")])))); + assert!(may_hold_approval(&lp(json!([script("a"), approval("b")])))); + // At any depth of inline loops. + assert!(may_hold_approval(&lp(json!([lp(json!([approval("b")]))])))); + assert!(may_hold_approval( + &json!({"id": "w", "value": {"type": "whileloopflow", + "modules": [{"id": "sub", "value": {"type": "flow", "path": "f/a/b"}}]}}) + )); + let branches = |kind, default, branch| { + json!({"id": "br", "value": {"type": kind, "default": default, + "branches": [{"modules": branch}]}}) + }; + assert!(!may_hold_approval(&branches( + "branchone", + json!([script("a")]), + json!([script("b")]) + ))); + assert!(may_hold_approval(&branches( + "branchone", + json!([approval("a")]), + json!([]) + ))); + assert!(may_hold_approval(&branches( + "branchone", + json!([]), + json!([approval("b")]) + ))); + assert!(may_hold_approval(&branches( + "branchall", + json!(null), + json!([approval("b")]) + ))); + assert!(!may_hold_approval(&branches( + "branchall", + json!(null), + json!([script("b")]) + ))); + // A step's own suspend is the caller's own approval, not a nested one. + assert!(!may_hold_approval(&approval("a"))); + // `"suspend": null` is not an approval step. + let mut nulled = script("a"); + nulled["suspend"] = serde_json::Value::Null; + assert!(!may_hold_approval(&lp(json!([nulled])))); + } + + #[test] + fn holders_reach_into_nested_loop_bodies() { + // A loop run's own definition keeps the inner loop as a `modules_node` reference, so + // the inner loop is found only from the flow's full definition. + let inner = json!({"id": "inner", "value": {"type": "forloopflow", + "modules": [approval("s")]}}); + let outer = json!({"id": "outer", "value": {"type": "forloopflow", + "modules": [script("a"), inner]}}); + let mut holders = std::collections::HashSet::new(); + approval_holders(&[outer, script("z")], &mut holders); + assert_eq!(holders, ["outer", "inner"].map(String::from).into()); + } +} diff --git a/backend/windmill-api/src/jobs_recent_runs.rs b/backend/windmill-api/src/jobs_recent_runs.rs index 7d4b1778d6..ca0ec7e152 100644 --- a/backend/windmill-api/src/jobs_recent_runs.rs +++ b/backend/windmill-api/src/jobs_recent_runs.rs @@ -159,9 +159,19 @@ pub(crate) async fn list_recent_runs( ORDER BY c.completed_at DESC LIMIT $4) UNION ALL - (SELECT q.id, NULL, q.started_at, NULL, NULL + (SELECT q.id, + -- `suspend` also parks a workflow as code on its children or a sleep: only + -- a wait on an approval is one. + CASE WHEN q.suspend > 0 AND ( + s.flow_status->'modules'->((s.flow_status->>'step')::int)->>'type' + = 'WaitingForEvents' + OR s.workflow_as_code_status->'_checkpoint'->'pending_steps'->>'mode' + = 'approval' + ) THEN 'suspended' END, + q.started_at, NULL, NULL FROM v2_job_queue q JOIN v2_job j ON j.id = q.id + LEFT JOIN v2_job_status s ON s.id = q.id WHERE q.workspace_id = $1 AND q.running AND {LISTED_ROOT_RUN} AND NOT EXISTS (SELECT 1 FROM v2_job_completed c WHERE c.id = q.id)) ) @@ -176,6 +186,7 @@ pub(crate) async fn list_recent_runs( 'script') = 'flow' THEN 'flow' ELSE 'script' END AS kind, CASE WHEN r.status IS NULL THEN 'running' + WHEN r.status = 'suspended' THEN 'suspended' WHEN r.status IN ('success', 'skipped') THEN 'success' WHEN r.status = 'canceled' THEN 'canceled' WHEN EXISTS (SELECT 1 FROM job_resolution jr WHERE jr.job_id = r.id) THEN 'resolved' diff --git a/backend/windmill-api/src/lib.rs b/backend/windmill-api/src/lib.rs index b1d3f60c76..e79cf8bd41 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -66,6 +66,7 @@ use windmill_common::{utils::GIT_VERSION, INSTANCE_NAME}; use crate::scim_oss::has_scim_token; use windmill_common::error::AppError; +mod admin_reliance; mod ai; #[cfg(feature = "private")] mod ai_free_tier_ee; @@ -90,6 +91,7 @@ mod azure_proxy_oss; mod capture; mod concurrency_groups; mod csrf; +mod explicit_credential; mod db; mod db_health; mod dbt; @@ -323,6 +325,49 @@ async fn set_request_client( windmill_common::trigger_history::scope_client(client, next.run(req)).await } +/// Refuses, before routing and authentication, a request from an address the instance IP +/// allowlist does not admit. +async fn enforce_instance_ip_allowlist( + req: axum::extract::Request, + next: axum::middleware::Next, +) -> axum::response::Response { + if let Some(ip) = windmill_common::instance_ip_allowlist::refused( + req.uri().path(), + req.extensions(), + req.headers(), + ) + .await + { + return axum::response::IntoResponse::into_response(( + http::StatusCode::FORBIDDEN, + format!( + "This Windmill instance does not accept requests from {ip}: it is not in the \ + instance IP allowlist." + ), + )); + } + next.run(req).await +} + +/// Scope the request in its origin (client address and user agent), recorded on the audit +/// entries it writes. A request routed in-process has no connect info and keeps the origin +/// of the request that routed it. +async fn set_request_origin( + req: axum::extract::Request, + next: axum::middleware::Next, +) -> axum::response::Response { + use windmill_common::request_origin::{current, scope, RequestOrigin}; + let peer = req + .extensions() + .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>() + .map(|c| c.0.ip()); + let origin = match (peer, current()) { + (None, Some(outer)) => (*outer).clone(), + (peer, _) => RequestOrigin::from_request(peer, req.headers()), + }; + scope(origin, next.run(req)).await +} + #[cfg(not(feature = "tantivy"))] type IndexReader = (); @@ -403,6 +448,9 @@ async fn inject_agent_authed( credential_expiry: None, mcp_client: None, capabilities: None, + allowed_ips: None, + admin_withheld: false, + super_admin_withheld: false, }, job_id: None, }); @@ -423,6 +471,8 @@ pub async fn run_server( ) -> anyhow::Result<()> { let user_db = UserDB::new(db.clone()); + windmill_common::client_ip::init(killpill_rx.resubscribe()).await; + for x in [&*HUB_CACHE_DIR] { DirBuilder::new() .recursive(true) @@ -454,6 +504,7 @@ pub async fn run_server( .layer(Extension(auth_cache.clone())) .layer(Extension(job_index_reader)) .layer(Extension(log_index_reader)) + .layer(axum::middleware::from_fn(admin_reliance::hint_withheld_admin)) // .layer(Extension(index_writer)) .layer(axum::middleware::from_fn(session_hint::mirror_session_cookie)) .layer(CookieManagerLayer::new()) @@ -1036,11 +1087,13 @@ pub async fn run_server( }) .route( "/w/{workspace_id}/jobs/slack_approval/{job_id}", - get(slack_approvals::request_slack_approval), + get(slack_approvals::request_slack_approval) + .route_layer(axum::middleware::from_fn(explicit_credential::require_explicit_credential)), ) .route( "/w/{workspace_id}/jobs/teams_approval/{job_id}", - get(teams_approvals_oss::request_teams_approval), + get(teams_approvals_oss::request_teams_approval) + .route_layer(axum::middleware::from_fn(explicit_credential::require_explicit_credential)), ) .nest("/w/{workspace_id}/github_app", { #[cfg(feature = "enterprise")] @@ -1159,6 +1212,7 @@ pub async fn run_server( } }) .route("/version", get(git_v)) + .route("/client_ip", get(client_ip)) .nest("/health/status", health::status_service()) .route("/min_keep_alive_version", get(min_keep_alive_version)) .route("/uptodate", get(is_up_to_date)) @@ -1246,7 +1300,8 @@ pub async fn run_server( } }) .fallback(static_assets::static_handler) - .layer(middleware_stack); + .layer(middleware_stack) + .layer(axum::middleware::from_fn(enforce_instance_ip_allowlist)); let app = if disable_response_logs { app @@ -1292,6 +1347,8 @@ pub async fn run_server( let app = app.layer(axum::middleware::from_fn(set_request_client)); + let app = app.layer(axum::middleware::from_fn(set_request_origin)); + let app = app.layer(CatchPanicLayer::custom(|err| { tracing::error!("panic in handler, returning 500: {:?}", err); Response::builder() @@ -1308,7 +1365,10 @@ pub async fn run_server( let listener = listener.tap_io(move |tcp_stream| { let _ = tcp_stream.set_nodelay(!server_mode); }); - let server = axum::serve(listener, app.into_make_service()); + let server = axum::serve( + listener, + app.into_make_service_with_connect_info::<std::net::SocketAddr>(), + ); tracing::info!( instance = %*INSTANCE_NAME, @@ -1400,6 +1460,15 @@ async fn git_v() -> String { format!("CE {GIT_VERSION}") } +/// The caller's address as token IP allowlists see it, so a device can learn what to put in a +/// token's allowed IPs, and an admin can tell a proxy missing from `TRUSTED_PROXIES` (its own +/// address comes back). Unauthenticated: it tells the caller only where it is calling from. +async fn client_ip( + windmill_common::client_ip::ClientIp(ip): windmill_common::client_ip::ClientIp, +) -> String { + ip.map(|ip| ip.to_string()).unwrap_or_default() +} + async fn min_keep_alive_version() -> Json<serde_json::Value> { let worker = windmill_common::min_version::MIN_KEEP_ALIVE_VERSION; let agent = windmill_common::min_version::AGENT_MIN_KEEP_ALIVE_VERSION; diff --git a/backend/windmill-api/src/live_migrations.rs b/backend/windmill-api/src/live_migrations.rs index a620807902..01538727c6 100644 --- a/backend/windmill-api/src/live_migrations.rs +++ b/backend/windmill-api/src/live_migrations.rs @@ -367,8 +367,12 @@ async fn retire_legacy_audit_table(conn: &mut PgConnection) -> Result<(), Error> .await?; tx.execute("DROP TABLE audit").await?; tx.execute( - format!("CREATE VIEW audit AS SELECT {AUDIT_COLUMNS} FROM audit_partitioned WHERE false") - .as_str(), + format!( + "CREATE VIEW audit AS SELECT {AUDIT_COLUMNS}, client_ip, user_agent, peer_ip, \ + forwarded_for \ + FROM audit_partitioned WHERE false" + ) + .as_str(), ) .await?; tx.execute("GRANT ALL ON audit TO windmill_user, windmill_admin") diff --git a/backend/windmill-api/src/mcp/card.html b/backend/windmill-api/src/mcp/card.html index 1e916d39cb..ed2decfe23 100644 --- a/backend/windmill-api/src/mcp/card.html +++ b/backend/windmill-api/src/mcp/card.html @@ -8,7 +8,8 @@ The MCP Apps view the session's show tools draw (`CARD_URI` in `mod.rs`, `views.rs`): a run, a table of runs, drafts to review before deploying, or a workspace item, from whichever of `_meta["windmill/run" | "windmill/runs" | "windmill/review" | "windmill/item"]` - the result carries. It holds no credential: it acts by calling tools + the result carries, or else from `load_card` with the call the result's `structuredContent` + names (Claude hands a view no `_meta`). It holds no credential: it acts by calling tools through the host, as the user the connection belongs to. Everything it shows is set as text, never as markup: a run's result is whatever its script returned. --> @@ -378,6 +379,21 @@ function textOf(result) { return (result?.content ?? []).filter((c) => c.type === 'text').map((c) => c.text).join('\n'); } + // A show tool's `structuredContent` only names its call (`tool`): Claude hands the card no + // `_meta`, so the card loads what the call shows through `load_card`, which returns it in both. + function cardData(result) { + const named = result?.structuredContent?.tool; + return { ...(named ? {} : result?.structuredContent), ...result?._meta }; + } + // A host that refuses a card's call to an app-only tool still answers the show tool, whose + // `_meta` carries the same data. + async function load(tool, { workspace_id, ...args }) { + try { + return await callTool('load_card', { workspace_id, tool, arguments: args }); + } catch { + return callTool(tool, { workspace_id, ...args }); + } + } function el(tag, props = {}, ...children) { const node = document.createElement(tag); for (const [key, value] of Object.entries(props)) { @@ -1010,9 +1026,9 @@ redraw(); if (!node.job_id) return; try { - const result = await callTool('show_run', { workspace_id: run.workspace, id: node.job_id }); + const result = await load('show_run', { workspace_id: run.workspace, id: node.job_id }); if (selected?.token !== token) return; - selected.run = result?._meta?.['windmill/run'] ?? { status: 'error', result: textOf(result) }; + selected.run = cardData(result)['windmill/run'] ?? { status: 'error', result: textOf(result) }; } catch (e) { if (selected?.token !== token) return; selected.run = { status: 'error', result: e?.message ?? 'The step could not be read.' }; @@ -1211,7 +1227,7 @@ const id = run?.id; if (!id) return; try { - const result = await callTool('show_run', { workspace_id: run.workspace, id }); + const result = await load('show_run', { workspace_id: run.workspace, id }); if (run?.id === id) onResult(result); } catch { if (run?.id === id) refreshFailed(); @@ -1414,8 +1430,8 @@ const address = { type, path, ...(trigger_kind ? { trigger_kind } : {}) }; // The draft may have changed since it was shown: what would be deployed is read again, // and a different diff is shown in place of deploying it. - const check = await callTool('show_deploy_review', { workspace_id: workspace, items: [address] }); - const current = check?._meta?.['windmill/review']?.items?.[0]; + const check = await load('show_deploy_review', { workspace_id: workspace, items: [address] }); + const current = cardData(check)['windmill/review']?.items?.[0]; if (!current || current.digest !== item.digest) { Object.assign(item, { patch: undefined, note: undefined, error: undefined, digest: undefined, too_large: undefined }, current ?? { error: 'The draft could not be read again.' }); openDiffs.add(itemKey(item)); @@ -1693,8 +1709,17 @@ // ---------------------------------------------------------------- dispatch - function onResult(result) { - const meta = result?._meta ?? {}; + async function onResult(result) { + let meta = cardData(result); + const call = result?.structuredContent; + if (!Object.keys(meta).some((k) => k.startsWith('windmill/')) && call?.tool) { + try { + result = await load(call.tool, { workspace_id: call.workspace_id, ...call.arguments }); + } catch (e) { + result = { isError: true, content: [{ type: 'text', text: e?.message ?? 'The card could not be loaded.' }] }; + } + meta = cardData(result); + } if (meta['windmill/review']) return renderReview(meta['windmill/review']); if (meta['windmill/runs']) return renderRuns(meta['windmill/runs']); if (meta['windmill/item']) return renderItem(meta['windmill/item']); diff --git a/backend/windmill-api/src/mcp/core.rs b/backend/windmill-api/src/mcp/core.rs index 25507b4119..6a74ded2a2 100644 --- a/backend/windmill-api/src/mcp/core.rs +++ b/backend/windmill-api/src/mcp/core.rs @@ -18,7 +18,7 @@ use windmill_mcp::server::{ RunOutcome, SessionAccess, Tool, }; -use crate::auth::AuthCache; +use crate::auth::{AuthCache, Tokened}; use crate::db::ApiAuthed; use crate::jobs::{ result_to_response, run_wait_result_flow_by_path_internal, @@ -500,12 +500,16 @@ impl McpBackend for WindmillBackend { async fn resolve_workspace_auth( &self, - token: &str, + token: &McpToken, workspace_id: &str, ) -> BackendResult<ApiAuthed> { let authed = self .auth_cache - .get_authed(Some(workspace_id.to_string()), token) + .get_authed( + Some(workspace_id.to_string()), + &token.token, + token.client_ip, + ) .await .ok_or_else(|| { ErrorData::invalid_params( @@ -729,6 +733,11 @@ pub async fn extract_workspace_from_token( next: Next, ) -> Response { if let Some(token) = extract_gateway_token(&request) { + // `ApiAuthed` must resolve this same token: it otherwise picks its own, preferring + // the `token` cookie, while the session acts as the owner of `McpToken`. + request + .extensions_mut() + .insert(Tokened { token: token.clone() }); let t_hash = hash_token(&token); match sqlx::query!( "SELECT workspace_id, scopes FROM token WHERE token_hash = $1 AND (expiration > NOW() OR expiration IS NULL)", @@ -758,7 +767,13 @@ pub async fn extract_workspace_from_token( .is_some_and(|s| s.iter().any(|scope| scope.starts_with("mcp:"))); if is_mcp { request.extensions_mut().insert(MultiWorkspaceMcp); - request.extensions_mut().insert(McpToken(token)); + let client_ip = windmill_common::client_ip::client_ip_of( + request.extensions(), + request.headers(), + ); + request + .extensions_mut() + .insert(McpToken { token, client_ip }); } } } diff --git a/backend/windmill-api/src/mcp/oauth_server.rs b/backend/windmill-api/src/mcp/oauth_server.rs index f07f563b32..08a58b353f 100644 --- a/backend/windmill-api/src/mcp/oauth_server.rs +++ b/backend/windmill-api/src/mcp/oauth_server.rs @@ -252,6 +252,21 @@ fn supported_scopes() -> Vec<String> { scopes } +/// Splits a requested scope into its scope tokens (RFC 6749 §3.3: separated by spaces). +/// The consent page shows the scopes split on spaces alone, so any other separator or control +/// character is refused: Rust's `split_whitespace` also splits on U+0085 and tabs, which would +/// grant scope tokens the page displayed as part of another one. +fn parse_scope_param(scope: &str) -> std::result::Result<Vec<String>, &'static str> { + if scope.bytes().any(|b| !(0x20..=0x7e).contains(&b)) { + return Err("scope may only hold printable ASCII scope tokens separated by spaces"); + } + Ok(scope + .split(' ') + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect()) +} + /// GET /.well-known/oauth-authorization-server/api/w/:workspace_id/mcp/oauth/server /// /// `client_base_url` serves what the MCP client calls itself, `base_url` the authorization @@ -523,9 +538,9 @@ async fn handle_authorization_code_grant( // Create access token (rejects archived workspaces inline) let rows = sqlx::query!( - "INSERT INTO token (token_hash, token_prefix, token, email, label, expiration, scopes, workspace_id, super_admin) + "INSERT INTO token (token_hash, token_prefix, token, email, label, expiration, scopes, workspace_id, super_admin, admin) SELECT $1::varchar, $2::varchar, $3::varchar, $4::varchar, $5::varchar, now() + ($6 || ' seconds')::interval, $7::text[], $8::varchar, - $9::bool AND COALESCE((SELECT super_admin FROM password WHERE email = $4), false) + $9::bool AND COALESCE((SELECT super_admin FROM password WHERE email = $4), false), true WHERE NOT EXISTS(SELECT 1 FROM workspace WHERE id = $8 AND deleted = true)", access_token_hash, access_token_prefix, @@ -684,9 +699,9 @@ async fn handle_refresh_token_grant( // Create new access token (rejects archived workspaces inline) let rows = sqlx::query!( - "INSERT INTO token (token_hash, token_prefix, token, email, label, expiration, scopes, workspace_id, super_admin) + "INSERT INTO token (token_hash, token_prefix, token, email, label, expiration, scopes, workspace_id, super_admin, admin) SELECT $1::varchar, $2::varchar, $3::varchar, $4::varchar, $5::varchar, now() + ($6 || ' seconds')::interval, $7::text[], $8::varchar, - $9::bool AND COALESCE((SELECT super_admin FROM password WHERE email = $4), false) + $9::bool AND COALESCE((SELECT super_admin FROM password WHERE email = $4), false), true WHERE NOT EXISTS(SELECT 1 FROM workspace WHERE id = $8 AND deleted = true)", new_access_token_hash, new_access_token_prefix, @@ -786,6 +801,16 @@ async fn oauth_authorize_inner( .into_response(); } + if let Err(e) = parse_scope_param(params.scope.as_deref().unwrap_or_default()) { + return OAuthErrorRedirect::new( + ¶ms.redirect_uri, + "invalid_scope", + Some(e), + params.state.as_deref(), + ) + .into_response(); + } + let code_challenge = match ¶ms.code_challenge { Some(challenge) if !challenge.is_empty() => challenge.as_str(), _ => { @@ -837,7 +862,6 @@ async fn oauth_authorize_inner( serde_urlencoded::to_string(&[ (mode_key, mode_value), ("client_id", params.client_id.as_str()), - ("client_name", client.client_name.as_str()), ("redirect_uri", params.redirect_uri.as_str()), ("scope", params.scope.as_deref().unwrap_or("mcp:all")), ("state", params.state.as_deref().unwrap_or("")), @@ -885,6 +909,18 @@ async fn oauth_approve_inner( // (GHSA-hfh4-cx4h-3fcr). Guarded at the shared inner fn: both the workspaced and // the gateway approve route reach the exchange through here. forbid_elevated_job_token(db, &authed.email, authed.job_id).await?; + // The exchanged token carries no IP restriction, so approving would lift the caller's. + if authed.allowed_ips.is_some() { + return Err(Error::NotAuthorized( + "A token restricted to IP addresses cannot approve an MCP client".to_string(), + )); + } + // The exchanged token carries the owner's admin rights, so approving would lift the cap. + if authed.admin_withheld { + return Err(Error::NotAuthorized( + "A token without its owner's admin rights cannot approve an MCP client".to_string(), + )); + } let caller_restricted = authed .scopes @@ -940,11 +976,8 @@ async fn oauth_approve_inner( let code = format!("mcp-code-{}", rd_string(32)); - let mut scopes: Vec<String> = form - .scope - .split_whitespace() - .map(|s| s.to_string()) - .collect(); + let mut scopes = + parse_scope_param(&form.scope).map_err(|e| Error::BadRequest(e.to_string()))?; if scopes.iter().any(|s| s == "mcp:all") && !scopes.iter().any(|s| s == SESSION_SCOPE) { scopes.push(SESSION_SCOPE.to_string()); } @@ -1134,8 +1167,8 @@ pub async fn gateway_oauth_approve( workspace_ids.extend(form.workspace_id); } // A selection of scripts and flows names paths, which only mean something in one workspace. - if !scope.split_whitespace().any(|s| s == "mcp:all") - && (form.all_workspaces || workspace_ids.len() > 1) + let requested = parse_scope_param(&scope).map_err(|e| Error::BadRequest(e.to_string()))?; + if !requested.iter().any(|s| s == "mcp:all") && (form.all_workspaces || workspace_ids.len() > 1) { return Err(Error::BadRequest( "Selected scripts and flows come from one workspace: pick one".to_string(), @@ -1179,6 +1212,33 @@ pub async fn gateway_oauth_approve( .await } +#[derive(Debug, Serialize)] +pub struct RegisteredClient { + client_id: String, + client_name: String, + redirect_uris: Vec<String>, + created_at: chrono::DateTime<chrono::Utc>, +} + +/// GET /api/mcp/gateway/oauth/server/client/:client_id — what the consent page shows: the +/// authorization URL's own copy of the client name is the client's to choose. +pub async fn get_registered_client( + Extension(db): Extension<DB>, + _authed: ApiAuthed, + Path(client_id): Path<String>, +) -> Result<Json<RegisteredClient>> { + let client = sqlx::query_as!( + RegisteredClient, + "SELECT client_id, client_name, redirect_uris, created_at FROM mcp_oauth_server_client + WHERE client_id = $1", + client_id + ) + .fetch_optional(&db) + .await? + .ok_or_else(|| Error::NotFound("Unknown client_id".to_string()))?; + Ok(Json(client)) +} + /// Gateway approval form — same as ApprovalForm, plus the workspaces the token reaches: /// one binds the token to it, several are listed in its scopes. #[derive(Debug, Deserialize)] @@ -1233,12 +1293,35 @@ pub fn gateway_unauthed_service() -> Router { /// Gateway OAuth endpoints that require authentication /// Mounted at /api/mcp/gateway/oauth/server (inside authenticated section) pub fn gateway_authed_service() -> Router { - Router::new().route("/approve", post(gateway_oauth_approve)) + Router::new() + .route("/approve", post(gateway_oauth_approve)) + .route("/client/{client_id}", get(get_registered_client)) } #[cfg(test)] mod tests { - use super::{build_oauth_metadata, validate_redirect_uri}; + use super::{build_oauth_metadata, parse_scope_param, validate_redirect_uri}; + + #[test] + fn scope_param_splits_on_spaces_only() { + assert_eq!( + parse_scope_param(" mcp:scripts:f/x/* mcp:runnables_as_tools ").unwrap(), + vec!["mcp:scripts:f/x/*", "mcp:runnables_as_tools"] + ); + assert_eq!(parse_scope_param("").unwrap(), Vec::<String>::new()); + for scope in [ + "mcp:scripts:f/x/*\u{85}mcp:all", + "mcp:scripts:f/x/*\tmcp:all", + "mcp:scripts:f/x/*\nmcp:all", + "mcp:scripts:f/x/*\u{a0}mcp:all", + "mcp:scripts:f/x/*\u{2028}mcp:all", + ] { + assert!( + parse_scope_param(scope).is_err(), + "expected {scope:?} to be refused" + ); + } + } #[test] fn authorization_endpoint_stays_on_base_url() { diff --git a/backend/windmill-api/src/mcp/session.rs b/backend/windmill-api/src/mcp/session.rs index 2f91a8d591..f701f790a6 100644 --- a/backend/windmill-api/src/mcp/session.rs +++ b/backend/windmill-api/src/mcp/session.rs @@ -52,10 +52,10 @@ fn tool_title(name: &str) -> String { } /// The MCP Apps view a client that renders them draws these tools' results in. It draws -/// what the tool put in its result's `_meta` (`Ctx::view`), and acts by calling tools. -/// Hosts cache a view by its URI: bump the version when a change breaks the `_meta` shape -/// the deployed card reads. -pub(super) const CARD_URI: &str = "ui://windmill/card-v1"; +/// what the tool put in its result's `_meta` (`Ctx::view`), or loads it with `load_card` +/// from the call named in `structuredContent`, and acts by calling tools. Hosts cache a +/// view by its URI: bump the version when a change breaks what the deployed card reads. +pub(super) const CARD_URI: &str = "ui://windmill/card-v2"; const CARD_HTML: &str = include_str!("card.html"); /// The `ui://` views the session's tools render in, as `(uri, html)`. @@ -89,8 +89,12 @@ pub(super) fn session_tools(session_access: SessionAccess) -> Vec<Tool> { .filter(|(name, ..)| tools::view_allowed(name, access)) .map(|(name, description, schema)| { let mut meta = result_size_meta(); - meta.0 - .insert("ui".into(), json!({ "resourceUri": CARD_URI })); + let ui = if name == tools::LOAD_CARD { + json!({ "resourceUri": CARD_URI, "visibility": ["app"] }) + } else { + json!({ "resourceUri": CARD_URI }) + }; + meta.0.insert("ui".into(), ui); let Value::Object(schema) = schema else { unreachable!("a view tool's schema is an object") }; @@ -114,6 +118,7 @@ pub(super) async fn call_session_tool( name: &str, args: Value, ) -> BackendResult<CallToolResult> { + let call = json!({ "tool": name, "workspace_id": ctx.w_id, "arguments": args.clone() }); let outcome = tools::call_session_tool(ctx, name, args) .await @@ -137,11 +142,22 @@ pub(super) async fn call_session_tool( CallToolResult::success(content) }; if let Some((key, view)) = ctx.view.lock().unwrap().take() { + result.structured_content = Some(structured_content(name, call, key, &view)); result.meta = Some(MetaObject(Map::from_iter([(key.to_string(), view)]))); } Ok(result) } +/// Codex's and ChatGPT's models read `structuredContent`, so a show tool's names only its +/// call. `load_card`'s holds the card data: only the card calls it. +fn structured_content(name: &str, call: Value, key: &str, view: &Value) -> Value { + if name == tools::LOAD_CARD { + json!({ key: view }) + } else { + call + } +} + #[cfg(test)] mod tests { use super::*; @@ -163,6 +179,35 @@ mod tests { } } + /// The card loads its data through `load_card`; a model that could call it would read + /// every card's data, which the show tools keep out of its context. + #[test] + fn only_load_card_is_hidden_from_the_model() { + let app_only: Vec<String> = session_tools(SessionAccess::Full) + .into_iter() + .filter(|tool| { + let ui = tool.meta.as_ref().and_then(|m| m.0.get("ui")); + ui.and_then(|ui| ui.get("visibility")) == Some(&json!(["app"])) + }) + .map(|tool| tool.name.to_string()) + .collect(); + assert_eq!(app_only, [tools::LOAD_CARD]); + } + + #[test] + fn only_load_card_puts_card_data_in_structured_content() { + let call = json!({ "tool": "show_run", "workspace_id": "w", "arguments": { "id": "1" } }); + let view = json!({ "status": "success", "logs": "tick" }); + assert_eq!( + structured_content("show_run", call.clone(), "windmill/run", &view), + call + ); + assert_eq!( + structured_content(tools::LOAD_CARD, call, "windmill/run", &view), + json!({ "windmill/run": view }) + ); + } + /// The ChatGPT directory wants every hint explicit, and Claude's a title on every tool. #[test] fn every_session_tool_has_a_title_and_explicit_hints() { diff --git a/backend/windmill-api/src/mcp/utils.rs b/backend/windmill-api/src/mcp/utils.rs index 1330d7cbca..ff5c16cf35 100644 --- a/backend/windmill-api/src/mcp/utils.rs +++ b/backend/windmill-api/src/mcp/utils.rs @@ -426,6 +426,14 @@ pub fn substitute_path_params( args_map: &serde_json::Map<String, Value>, path_schema: &Option<Value>, ) -> BackendResult<String> { + // Global tools carry no workspace, and multi-workspace mode passes an empty one. + if path.contains("{workspace}") && !crate::ai_session_tools::is_plain_workspace_id(workspace_id) + { + return Err(ErrorData::invalid_params( + "Invalid workspace_id: only letters, digits, '_' and '-' are allowed".to_string(), + None, + )); + } let mut path_template = path.replace("{workspace}", workspace_id); if let Some(schema) = path_schema { @@ -718,7 +726,7 @@ pub async fn send_as_caller( body_json: Option<Value>, scopes: Option<Vec<String>>, ) -> BackendResult<reqwest::Response> { - let client = &HTTP_CLIENT; + let client = &crate::ai_session_tools::CALLER_HTTP_CLIENT; let mut request_builder = match method { "GET" => client.get(url), "POST" => client.post(url), @@ -1321,6 +1329,20 @@ mod tests { result.is_err(), "traversal payload must be rejected before URL substitution" ); + + args.insert("path".to_string(), json!("x")); + for workspace in ["x/../../settings/global/jwt_secret?", "a%2F..", "a.b", ""] { + assert!( + substitute_path_params( + "/w/{workspace}/resources/get/{path}", + workspace, + &args, + &path_schema, + ) + .is_err(), + "workspace {workspace:?} must be rejected" + ); + } } #[test] @@ -1467,6 +1489,9 @@ mod tests { credential_expiry: None, mcp_client: None, capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), + allowed_ips: None, + admin_withheld: false, + super_admin_withheld: false, } } diff --git a/backend/windmill-api/src/offboarding.rs b/backend/windmill-api/src/offboarding.rs index 8dc53a7c72..a912351bbb 100644 --- a/backend/windmill-api/src/offboarding.rs +++ b/backend/windmill-api/src/offboarding.rs @@ -85,10 +85,44 @@ fn default_true() -> bool { pub(crate) struct OffboardResponse { #[serde(skip_serializing_if = "Vec::is_empty")] conflicts: Vec<String>, + #[serde(skip_serializing_if = "Vec::is_empty")] + conflict_items: Vec<PathConflict>, #[serde(skip_serializing_if = "Option::is_none")] summary: Option<OffboardSummary>, } +impl OffboardResponse { + fn conflicts(conflict_items: Vec<PathConflict>, global: bool) -> Self { + let conflicts = conflict_items + .iter() + .map(|c| { + if global { + format!("[{}] {}: {}", c.workspace_id, c.kind, c.target_path) + } else { + format!("{}: {}", c.kind, c.target_path) + } + }) + .collect(); + Self { conflicts, conflict_items, summary: None } + } + + fn done(summary: OffboardSummary) -> Self { + Self { conflicts: vec![], conflict_items: vec![], summary: Some(summary) } + } +} + +/// An item of the departing user whose reassigned path is already taken. +#[derive(Serialize)] +struct PathConflict { + workspace_id: String, + /// The table the item lives in (`script`, `flow`, `http_trigger`, ...). + kind: String, + /// The departing user's item, under `u/{username}/`. + source_path: String, + /// The existing item the reassignment would collide with. + target_path: String, +} + #[derive(Serialize)] struct OffboardSummary { scripts_reassigned: i64, @@ -415,7 +449,7 @@ pub(crate) async fn offboard_workspace_user( let conflicts = check_path_conflicts(&db, &w_id, &username, &req.reassign_to).await?; if !conflicts.is_empty() { - return Ok(Json(OffboardResponse { conflicts, summary: None })); + return Ok(Json(OffboardResponse::conflicts(conflicts, false))); } let email = sqlx::query_scalar!( @@ -478,10 +512,7 @@ pub(crate) async fn offboard_workspace_user( .await?; } - Ok(Json(OffboardResponse { - conflicts: vec![], - summary: Some(summary), - })) + Ok(Json(OffboardResponse::done(summary))) } // ---- Instance-level endpoints ---- @@ -557,16 +588,11 @@ pub(crate) async fn offboard_global_user( &reassignment.reassign_to, ) .await?; - for c in conflicts { - all_conflicts.push(format!("[{}] {}", &ws.workspace_id, c)); - } + all_conflicts.extend(conflicts); } } if !all_conflicts.is_empty() { - return Ok(Json(OffboardResponse { - conflicts: all_conflicts, - summary: None, - })); + return Ok(Json(OffboardResponse::conflicts(all_conflicts, true))); } let mut tx = db.begin().await?; @@ -654,10 +680,7 @@ pub(crate) async fn offboard_global_user( tx.commit().await?; - Ok(Json(OffboardResponse { - conflicts: vec![], - summary: Some(total_summary), - })) + Ok(Json(OffboardResponse::done(total_summary))) } // ---- Validation helpers ---- @@ -769,7 +792,7 @@ async fn check_path_conflicts( w_id: &str, username: &str, reassign_to: &str, -) -> Result<Vec<String>> { +) -> Result<Vec<PathConflict>> { let new_prefix = format!("{}/", reassign_to); let mut conflicts = Vec::new(); @@ -800,11 +823,14 @@ async fn check_path_conflicts( "flow" => " AND NOT t1.archived", _ => "", }; + // A conflict is resolved by deleting one of its two paths, so the source must be the + // departing user's: `starts_with` rather than LIKE, where the `_` usernames may hold + // matches any character and would report another user's item as conflicting with itself. // SAFETY: `table_name` comes from a hardcoded allowlist `tables`, not user input. - let rows: Vec<String> = sqlx::query_scalar(&format!( - "SELECT REGEXP_REPLACE(t1.path, '^u/' || $1 || '/', $3) \ + let rows: Vec<(String, String)> = sqlx::query_as(&format!( + "SELECT DISTINCT t1.path, REGEXP_REPLACE(t1.path, '^u/' || $1 || '/', $3) \ FROM {table} t1 \ - WHERE t1.path LIKE ('u/' || $1 || '/%') AND t1.workspace_id = $2{extra_filter} \ + WHERE starts_with(t1.path, 'u/' || $1 || '/') AND t1.workspace_id = $2{extra_filter} \ AND EXISTS ( \ SELECT 1 FROM {table} t2 \ WHERE t2.path = REGEXP_REPLACE(t1.path, '^u/' || $1 || '/', $3) \ @@ -818,8 +844,13 @@ async fn check_path_conflicts( .fetch_all(db) .await?; - for path in rows { - conflicts.push(format!("{}: {}", table_name, path)); + for (source_path, target_path) in rows { + conflicts.push(PathConflict { + workspace_id: w_id.to_string(), + kind: table_name.to_string(), + source_path, + target_path, + }); } } @@ -1216,12 +1247,47 @@ async fn offboard_user_from_workspace<'c>( &new_prefix, username, w_id ).execute(&mut **tx).await?; + // Deleting a script or flow by path leaves its asset usages behind, on the keys the moved + // usages take; such a row is an orphan or the same usage, so it is dropped, not renamed onto. + sqlx::query( + "DELETE FROM asset d WHERE d.workspace_id = $3 AND EXISTS ( \ + SELECT 1 FROM asset s \ + WHERE s.workspace_id = $3 AND starts_with(s.usage_path, 'u/' || $2 || '/') \ + AND s.ctid <> d.ctid AND s.path = d.path AND s.kind = d.kind AND s.usage_kind = d.usage_kind \ + AND REGEXP_REPLACE(s.usage_path, '^u/' || $2 || '/(.*)', $1 || '/\\1') = d.usage_path)", + ) + .bind(&new_prefix) + .bind(username) + .bind(w_id) + .execute(&mut **tx) + .await?; + sqlx::query!( r#"UPDATE asset SET usage_path = REGEXP_REPLACE(usage_path, 'u/' || $2 || '/(.*)', $1 || '/\1') WHERE usage_path LIKE ('u/' || $2 || '/%') AND workspace_id = $3"#, &new_prefix, username, w_id ).execute(&mut **tx).await?; // ---- dependency_map ---- + // Deleting an item by path leaves its rows here, so an item deleted to make room at the + // target still holds the keys the moved rows take. A row already holding a moved row's final + // key is such an orphan or the same edge, so it is dropped rather than renamed onto. + // SAFETY: `column` comes from the hardcoded list below, not user input. + for column in ["importer_path", "imported_path"] { + sqlx::query(&format!( + "DELETE FROM dependency_map d WHERE d.workspace_id = $3 AND EXISTS ( \ + SELECT 1 FROM dependency_map s \ + WHERE s.workspace_id = $3 AND starts_with(s.{column}, 'u/' || $2 || '/') \ + AND s.ctid <> d.ctid AND s.importer_node_id = d.importer_node_id AND s.importer_kind = d.importer_kind \ + AND REGEXP_REPLACE(s.importer_path, '^u/' || $2 || '/(.*)', $1 || '/\\1') = d.importer_path \ + AND REGEXP_REPLACE(s.imported_path, '^u/' || $2 || '/(.*)', $1 || '/\\1') = d.imported_path)" + )) + .bind(&new_prefix) + .bind(username) + .bind(w_id) + .execute(&mut **tx) + .await?; + } + sqlx::query!( r#"UPDATE dependency_map SET importer_path = REGEXP_REPLACE(importer_path, 'u/' || $2 || '/(.*)', $1 || '/\1') WHERE importer_path LIKE ('u/' || $2 || '/%') AND workspace_id = $3"#, &new_prefix, username, w_id diff --git a/backend/windmill-api/src/resources.rs b/backend/windmill-api/src/resources.rs index 803927e43c..49518c4a4d 100644 --- a/backend/windmill-api/src/resources.rs +++ b/backend/windmill-api/src/resources.rs @@ -1,5 +1,5 @@ #[cfg(feature = "mcp")] -use axum::routing::{get, post}; +use axum::routing::post; use axum::Router; /// Wraps the subcrate's workspaced_service with the mcp_tools routes @@ -9,9 +9,12 @@ pub fn workspaced_service() -> Router { #[cfg(feature = "mcp")] use crate::mcp_tools::{call_mcp_tool, get_mcp_tools}; + // Listing tools sends the caller's resolved secrets to the URL the resource names, so it + // is a POST: the `SameSite=Lax` session cookie rides on a cross-site link or redirect to a + // GET, which would let anyone who can share a link pick the resource for the caller. #[cfg(feature = "mcp")] let router = router - .route("/mcp_tools/{*path}", get(get_mcp_tools)) + .route("/mcp_tools/{*path}", post(get_mcp_tools)) .route("/mcp_call_tool/{*path}", post(call_mcp_tool)); router diff --git a/backend/windmill-api/src/token.rs b/backend/windmill-api/src/token.rs index 7428e586d6..35287ffc34 100644 --- a/backend/windmill-api/src/token.rs +++ b/backend/windmill-api/src/token.rs @@ -1,7 +1,24 @@ -use axum::{routing::get, Json, Router}; +use std::sync::Arc; + +use axum::{ + extract::Query, + routing::{get, post}, + Extension, Json, Router, +}; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; -use windmill_common::error::JsonResult; +use windmill_api_auth::{ + auth::{check_route_layer, maybe_get_workspace_id_from_path}, + check_scopes, AuthCache, OptJobAuthed, Tokened, +}; +use windmill_common::{ + auth::{hash_token, is_session_label, is_super_admin_email, JWTAuthClaims}, + client_ip::ClientIp, + error::{Error, JsonResult}, + jwt, + users::SUPERADMIN_SECRET_EMAIL, + DB, +}; #[derive(Default, Serialize, Deserialize, Clone)] pub struct ScopeOption { @@ -191,7 +208,7 @@ fn build_standard_scope_domains() -> Vec<ScopeDomain> { } lazy_static! { - static ref ALL_SCOPES: Vec<ScopeDomain> = { + pub(crate) static ref ALL_SCOPES: Vec<ScopeDomain> = { let mut groups = vec![ScopeDomain { name: "Jobs".to_string(), description: Some("Job management".to_string()), @@ -285,7 +302,295 @@ lazy_static! { } pub fn global_service() -> Router { - Router::new().route("/list/scopes", get(get_all_available_scopes)) + Router::new() + .route("/list/scopes", get(get_all_available_scopes)) + .route("/introspect", get(introspect_token)) + .route("/admin_reliance", post(crate::admin_reliance::admin_reliance)) +} + +#[derive(Deserialize)] +struct IntrospectQuery { + workspace: Option<String>, + path: Option<String>, + method: Option<String>, +} + +#[derive(Serialize)] +struct TokenIntrospection { + kind: &'static str, + email: String, + username: String, + #[serde(skip_serializing_if = "Option::is_none")] + label: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + token_prefix: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + created_at: Option<chrono::DateTime<chrono::Utc>>, + #[serde(skip_serializing_if = "Option::is_none")] + expiration: Option<chrono::DateTime<chrono::Utc>>, + #[serde(skip_serializing_if = "Option::is_none")] + workspace_id: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + workspace_ids: Option<Vec<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + scopes: Option<Vec<String>>, + read_only: bool, + /// The token does not carry its owner's workspace admin rights. + admin_withheld: bool, + /// The token reaches superadmin routes: its owner is a superadmin and the token neither + /// withholds that nor is a job's. + super_admin: bool, + #[serde(skip_serializing_if = "Option::is_none")] + allowed_ips: Option<Vec<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + job_id: Option<uuid::Uuid>, + #[serde(skip_serializing_if = "Option::is_none")] + workspace: Option<TokenWorkspaceAccess>, + #[serde(skip_serializing_if = "Option::is_none")] + route: Option<TokenRouteCheck>, +} + +#[derive(Serialize)] +struct TokenWorkspaceAccess { + workspace_id: String, + usable: bool, + #[serde(skip_serializing_if = "Option::is_none")] + is_admin: Option<bool>, + #[serde(skip_serializing_if = "Option::is_none")] + is_operator: Option<bool>, + #[serde(skip_serializing_if = "Option::is_none")] + groups: Option<Vec<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + folders: Option<Vec<FolderAccess>>, +} + +#[derive(Serialize)] +struct FolderAccess { + name: String, + write: bool, + owner: bool, +} + +#[derive(Serialize)] +struct TokenRouteCheck { + method: String, + path: String, + allowed: bool, + #[serde(skip_serializing_if = "Option::is_none")] + reason: Option<String>, +} + +/// The scope a run-by-path endpoint (`windmill-api/src/jobs.rs`) requires of the runnable once +/// the route layer has admitted the token, which only knows that it may run something. Routes +/// added there with their own `check_scopes` belong here too, or the verdict over-reports. +fn run_by_path_scope(path: &str) -> Option<String> { + let (_, suffix) = path.strip_prefix("/api/w/")?.split_once('/')?; + let (endpoint, rest) = suffix.strip_prefix("jobs/")?.split_once('/')?; + if !matches!( + endpoint, + "run" | "run_wait_result" | "run_and_stream" | "run_inline" + ) { + return None; + } + let kind = match rest.split_once('/')? { + ("p", runnable) => ("scripts", runnable), + ("f", runnable) if endpoint != "run_inline" => ("flows", runnable), + _ => return None, + }; + Some(format!("jobs:run:{}:{}", kind.0, kind.1)) +} + +/// Describes only the credential presenting the request (`Tokened`), never one named in the +/// request, so it cannot be used to look up another person's token. It resolves the token +/// itself rather than through `ApiAuthed`: the route layer would refuse a scoped token here, +/// and a workspace-bound token resolves on no route outside its workspace. +async fn introspect_token( + Extension(db): Extension<DB>, + Extension(cache): Extension<Arc<AuthCache>>, + Tokened { token }: Tokened, + ClientIp(client_ip): ClientIp, + Query(q): Query<IntrospectQuery>, +) -> JsonResult<TokenIntrospection> { + let unauthorized = || Error::NotAuthorized("Unauthorized".to_string()); + let row = if token.starts_with("jwt_") { + None + } else { + sqlx::query!( + "SELECT owner, email, label, token_prefix, created_at, expiration, workspace_id, + scopes, read_only, super_admin, admin, allowed_ips::text[] AS allowed_ips + FROM token + WHERE token_hash = $1 AND (expiration > NOW() OR expiration IS NULL)", + hash_token(&token) + ) + .fetch_optional(&db) + .await? + }; + + let mut out = if let Some(row) = row { + let allowed = + windmill_api_auth::token_ip_allowlist_oss::load_allowed_ips(row.allowed_ips.clone()); + if !windmill_api_auth::client_ip_allowed(allowed.as_deref(), client_ip) { + return Err(unauthorized()); + } + let email = row.email.ok_or_else(unauthorized)?; + let is_session = is_session_label(row.label.as_deref()); + TokenIntrospection { + kind: if is_session { "session" } else { "api_token" }, + username: row + .owner + .as_deref() + .and_then(|o| o.split_once('/')) + .map(|(_, name)| name.to_string()) + .unwrap_or_else(|| email.clone()), + email, + label: row.label, + token_prefix: Some(row.token_prefix), + created_at: Some(row.created_at), + expiration: row.expiration, + workspace_id: row.workspace_id, + workspace_ids: None, + scopes: row.scopes, + read_only: row.read_only, + admin_withheld: !row.admin, + // Not withheld yet; whether the owner holds it is settled below. A session + // always stands for the account as it is. + super_admin: row.super_admin || is_session, + // What the build enforces: a CE build ignores a stored list. + allowed_ips: allowed.map(|nets| nets.iter().map(|n| n.to_string()).collect()), + job_id: None, + workspace: None, + route: None, + } + } else { + // A guest JWT resolves only inside its workspace. + let requested = q.workspace.clone().filter(|w| !w.is_empty()); + let resolved = match cache.get_opt_job_authed(None, &token, client_ip).await { + Some(resolved) => Some(resolved), + None if requested.is_some() => { + cache.get_opt_job_authed(requested, &token, client_ip).await + } + None => None, + }; + let OptJobAuthed { authed, job_id } = resolved.ok_or_else(unauthorized)?; + let mut out = TokenIntrospection { + kind: if authed.email == SUPERADMIN_SECRET_EMAIL { + "superadmin_secret" + } else { + "external" + }, + email: authed.email, + username: authed.username, + label: None, + token_prefix: None, + created_at: None, + expiration: None, + workspace_id: None, + workspace_ids: None, + scopes: authed.scopes, + read_only: authed.read_only, + admin_withheld: authed.admin_withheld, + super_admin: !authed.super_admin_withheld, + allowed_ips: None, + job_id, + workspace: None, + route: None, + }; + if let Some(jwt) = token + .strip_prefix("jwt_") + .filter(|_| !token.starts_with("jwt_ext_")) + { + out.kind = "jwt"; + if let Ok(claims) = jwt::decode_with_internal_secret::<JWTAuthClaims>(jwt).await { + out.label = claims.label; + out.workspace_id = claims.workspace_id; + out.workspace_ids = claims.workspace_ids; + out.expiration = chrono::DateTime::from_timestamp(claims.exp as i64, 0); + } + } + out + }; + // The same three conditions `require_super_admin` checks. + out.super_admin = + out.super_admin && out.job_id.is_none() && is_super_admin_email(&db, &out.email).await?; + + if let Some(w_id) = q.workspace.as_deref().filter(|w| !w.is_empty()) { + let resolved = cache + .get_opt_job_authed(Some(w_id.to_string()), &token, client_ip) + .await; + out.workspace = Some(match resolved { + Some(OptJobAuthed { authed, .. }) => TokenWorkspaceAccess { + workspace_id: w_id.to_string(), + usable: true, + is_admin: Some(authed.is_admin), + is_operator: Some(authed.is_operator), + groups: Some(authed.groups), + folders: Some( + authed + .folders + .into_iter() + .map(|(name, write, owner)| FolderAccess { name, write, owner }) + .collect(), + ), + }, + None => TokenWorkspaceAccess { + workspace_id: w_id.to_string(), + usable: false, + is_admin: None, + is_operator: None, + groups: None, + folders: None, + }, + }); + } + + if let Some(path) = q.path.as_deref().map(str::trim).filter(|p| !p.is_empty()) { + let path = if path.starts_with("/api/") { + path.to_string() + } else if let Some(w_id) = q.workspace.as_deref().filter(|w| !w.is_empty()) { + format!("/api/w/{w_id}/{}", path.trim_start_matches('/')) + } else { + return Err(Error::BadRequest( + "a relative path needs a workspace; pass a full /api/... path".to_string(), + )); + }; + let path = path + .split(['?', '#']) + .next() + .unwrap_or_default() + .to_string(); + let method = q.method.as_deref().unwrap_or("GET").to_ascii_uppercase(); + let path_vec: Vec<&str> = path.split('/').collect(); + let route_workspace = maybe_get_workspace_id_from_path(&path_vec); + let resolved = cache + .get_opt_job_authed(route_workspace.clone(), &token, client_ip) + .await; + let verdict = match resolved { + None => Err(match route_workspace.as_deref() { + Some(w_id) => format!("The token cannot be used in workspace {w_id}."), + None => "The token cannot be used outside a workspace.".to_string(), + }), + Some(mut opt_job_authed) => async { + check_route_layer( + &db, + &mut opt_job_authed, + route_workspace.as_deref(), + &path, + &method, + ) + .await?; + if let Some(scope) = run_by_path_scope(&path) { + check_scopes(&opt_job_authed.authed, || scope)?; + } + Ok::<_, Error>(()) + } + .await + .map_err(|e| e.to_string()), + }; + out.route = + Some(TokenRouteCheck { method, path, allowed: verdict.is_ok(), reason: verdict.err() }); + } + + Ok(Json(out)) } async fn get_all_available_scopes() -> JsonResult<Vec<ScopeDomain>> { @@ -296,6 +601,22 @@ async fn get_all_available_scopes() -> JsonResult<Vec<ScopeDomain>> { mod tests { use super::*; + #[test] + fn run_by_path_scope_names_the_runnable() { + let scope = |p: &str| run_by_path_scope(p); + assert_eq!( + scope("/api/w/ws/jobs/run_wait_result/p/f/ci/build").as_deref(), + Some("jobs:run:scripts:f/ci/build") + ); + assert_eq!( + scope("/api/w/ws/jobs/run/f/u/me/flow").as_deref(), + Some("jobs:run:flows:u/me/flow") + ); + assert_eq!(scope("/api/w/ws/jobs/run/h/abc"), None); + assert_eq!(scope("/api/w/ws/jobs/run_inline/f/u/me/flow"), None); + assert_eq!(scope("/api/w/ws/scripts/list"), None); + } + /// The token-scope picker is driven by this catalog, so a scope that is /// enforced but absent here can't be granted through the supported UI. #[test] diff --git a/backend/windmill-api/src/triggers/http/handler.rs b/backend/windmill-api/src/triggers/http/handler.rs index 402cc28696..bd11383d44 100644 --- a/backend/windmill-api/src/triggers/http/handler.rs +++ b/backend/windmill-api/src/triggers/http/handler.rs @@ -368,6 +368,7 @@ async fn get_http_route_trigger( route_path: &str, auth_cache: &Arc<AuthCache>, token: Option<&String>, + client_ip: Option<std::net::IpAddr>, db: &DB, user_db: UserDB, method: &http::Method, @@ -408,12 +409,19 @@ async fn get_http_route_trigger( let username_override = if let AuthenticationMethod::Windmill = trigger.authentication_method { let opt_authed = if let Some(token) = token { auth_cache - .get_authed(Some(trigger.workspace_id.clone()), token) + .get_authed(Some(trigger.workspace_id.clone()), token, client_ip) .await } else { None }; if let Some(authed) = opt_authed { + // `/r/*` bypasses the `ApiAuthed` read-only check, and a route without static + // assets runs its runnable whatever the method, so a read-only token is refused. + if authed.read_only && trigger.static_asset_config.is_none() { + return Err(Error::PermissionDenied( + "Token is read-only. Triggering HTTP routes is not allowed.".to_string(), + )); + } check_scopes(&authed, || format!("http_triggers:read:{}", &trigger.path))?; // check that the user has access to the trigger @@ -496,6 +504,7 @@ async fn route_job( Extension(auth_cache): Extension<Arc<AuthCache>>, Extension(cors_policy): Extension<ResolvedCorsPolicy>, OptTokened { token }: OptTokened, + windmill_common::client_ip::ClientIp(client_ip): windmill_common::client_ip::ClientIp, Path(route_path): Path<StripPath>, headers: HeaderMap, args: RawHttpTriggerArgs, @@ -506,6 +515,7 @@ async fn route_job( route_path, &auth_cache, token.as_ref(), + client_ip, &db, user_db.clone(), &args.0.metadata.method, diff --git a/backend/windmill-api/src/workspaces.rs b/backend/windmill-api/src/workspaces.rs index b3a7160630..778d24ed2a 100644 --- a/backend/windmill-api/src/workspaces.rs +++ b/backend/windmill-api/src/workspaces.rs @@ -275,6 +275,7 @@ pub async fn get_critical_alerts( &authed.username, &authed.email, authed.job_id.is_some(), + authed.super_admin_withheld, &db, ) .await?; @@ -298,6 +299,7 @@ pub async fn acknowledge_critical_alert( &authed.username, &authed.email, authed.job_id.is_some(), + authed.super_admin_withheld, &db, ) .await?; diff --git a/backend/windmill-audit/src/instance_config.rs b/backend/windmill-audit/src/instance_config.rs index 977e0fe6c6..85b00a5560 100644 --- a/backend/windmill-audit/src/instance_config.rs +++ b/backend/windmill-audit/src/instance_config.rs @@ -54,9 +54,14 @@ fn parameters<'a>( (!parameters.is_empty()).then_some(parameters) } -/// A setting is recorded by name, with its value only when that is a boolean or a number. -/// Any other shape can carry a credential (a registry URL, a webhook, a header map), and no -/// list of secret-bearing settings stays complete as settings are added. +/// Settings whose whole value is recorded: their shape is fixed and holds no credential. +const RECORDED_IN_FULL: &[&str] = + &[windmill_common::global_settings::INSTANCE_IP_ALLOWLIST_SETTING]; + +/// A setting is recorded by name, with its value only when that is a boolean or a number, or +/// the setting is in [`RECORDED_IN_FULL`]. Any other shape can carry a credential (a registry +/// URL, a webhook, a header map), and no list of secret-bearing settings stays complete as +/// settings are added. /// /// AUTHORIZATION: records a write, checks nothing. The caller must have established that /// `author` may change instance settings before performing the write this records. @@ -76,6 +81,7 @@ pub async fn audit_setting_write( Some(v @ (serde_json::Value::Bool(_) | serde_json::Value::Number(_))) => { Some(v.to_string()) } + Some(v) if !deleted && RECORDED_IN_FULL.contains(&key) => Some(v.to_string()), _ => None, }; audit_log( diff --git a/backend/windmill-audit/src/lib.rs b/backend/windmill-audit/src/lib.rs index 89b5de067a..9acd32bc56 100644 --- a/backend/windmill-audit/src/lib.rs +++ b/backend/windmill-audit/src/lib.rs @@ -26,6 +26,14 @@ pub struct AuditLog { pub resource: Option<String>, pub parameters: Option<serde_json::Value>, pub span: Option<String>, + #[sqlx(default)] + pub client_ip: Option<String>, + #[sqlx(default)] + pub user_agent: Option<String>, + #[sqlx(default)] + pub peer_ip: Option<String>, + #[sqlx(default)] + pub forwarded_for: Option<String>, } #[derive(Deserialize)] diff --git a/backend/windmill-common/Cargo.toml b/backend/windmill-common/Cargo.toml index c44679b611..c5ed308a60 100644 --- a/backend/windmill-common/Cargo.toml +++ b/backend/windmill-common/Cargo.toml @@ -17,7 +17,8 @@ benchmark = [] parquet = [] aws_auth = ["dep:aws-sdk-sts", "dep:aws-config"] otel = ["dep:opentelemetry-semantic-conventions", "dep:opentelemetry-otlp", "dep:opentelemetry_sdk", - "dep:tracing-opentelemetry", "dep:opentelemetry-appender-tracing", "dep:tonic", "dep:opentelemetry"] + "dep:tracing-opentelemetry", "dep:opentelemetry-appender-tracing", "dep:tonic", "dep:opentelemetry", + "dep:opentelemetry-http", "dep:reqwest_otel"] smtp = ["dep:mail-send", "dep:rustls", "dep:tokio-rustls", "dep:rustls-native-certs", "dep:webpki-roots"] scoped_cache = [] cloud = [] @@ -142,6 +143,9 @@ opentelemetry = { workspace = true, optional = true } tracing-opentelemetry = { workspace = true, optional = true } opentelemetry-appender-tracing = { workspace = true, optional = true } tonic = { workspace = true, optional = true } +opentelemetry-http = { workspace = true, optional = true } +# The reqwest the OTLP/HTTP exporter is built on, for a client of our own around it. +reqwest_otel = { package = "reqwest", version = "0.12", features = ["blocking"], optional = true } equivalent = "1.0.2" [dev-dependencies] diff --git a/backend/windmill-common/src/auth.rs b/backend/windmill-common/src/auth.rs index b91bdf68a8..db56fdbf6c 100644 --- a/backend/windmill-common/src/auth.rs +++ b/backend/windmill-common/src/auth.rs @@ -30,6 +30,8 @@ use crate::{ /// - the `update_token_label` editability guard (SQL `WHERE`) in /// windmill-api-users/src/users.rs /// - `isUserToken` in frontend/src/lib/components/settings/TokensTable.svelte +/// - `self_managed` in the `token_risk` view (a migration), for a label the server also expires or +/// renews on its own pub fn is_user_token(label: Option<&str>) -> bool { match label { None => true, @@ -346,6 +348,13 @@ pub struct JWTAuthClaims { /// records the client on the runs it starts. #[serde(default, skip_serializing_if = "Option::is_none")] pub mcp_client: Option<String>, + /// The rights the credential this JWT was minted from withholds from its owner (a token's + /// `admin` / `super_admin`), which `is_admin` alone cannot carry: superadmin gates key off + /// the email, and `tokens/create` would otherwise mint them back. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub admin_withheld: bool, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub super_admin_withheld: bool, } impl JWTAuthClaims { @@ -841,6 +850,31 @@ pub async fn create_jwt_token( label: Option<String>, audit_span: Option<String>, scopes: Option<Vec<String>>, +) -> crate::error::Result<String> { + create_jwt_token_withholding( + authed, + workspace_id, + expires_in_seconds, + job_id, + label, + audit_span, + scopes, + (false, false), + ) + .await +} + +/// [`create_jwt_token`] for a JWT minted from a caller's credential, carrying the +/// `(admin, super_admin)` rights that credential withholds. +pub async fn create_jwt_token_withholding( + authed: Authed, + workspace_id: &str, + expires_in_seconds: u64, + job_id: Option<Uuid>, + label: Option<String>, + audit_span: Option<String>, + scopes: Option<Vec<String>>, + (admin_withheld, super_admin_withheld): (bool, bool), ) -> crate::error::Result<String> { let payload = JWTAuthClaims { email: authed.email.clone(), @@ -858,6 +892,8 @@ pub async fn create_jwt_token( scopes, audit_span, mcp_client: authed.mcp_client.clone(), + admin_withheld, + super_admin_withheld, }; let token = jwt::encode_with_internal_secret(&payload) @@ -997,6 +1033,8 @@ mod tests { scopes: None, audit_span: None, mcp_client: None, + admin_withheld: false, + super_admin_withheld: false, }; // Signature is irrelevant — the gate decodes without verifying — so any key works. let token = jsonwebtoken::encode( diff --git a/backend/windmill-common/src/cache.rs b/backend/windmill-common/src/cache.rs index c97ee97505..d64af59015 100644 --- a/backend/windmill-common/src/cache.rs +++ b/backend/windmill-common/src/cache.rs @@ -626,6 +626,25 @@ pub mod flow { }); fut.map_ok(|Entry(data)| data) } + + /// A full version (from [`fetch_version`]) shaped as its lite row would be for running it: + /// a trailing suspend or sleep only takes effect through the virtual step after it, which + /// the dependency job writes into the lite row. Running from the full version without it + /// would end the flow at the suspended step. + pub fn as_run_version(data: Arc<FlowData>) -> error::Result<Arc<FlowData>> { + let needs_virtual = data + .value() + .modules + .last() + .is_some_and(|m| m.sleep.is_some() || m.suspend.is_some()); + if !needs_virtual { + return Ok(data); + } + let mut value = data.value().clone(); + crate::flows::add_virtual_items_if_necessary(&mut value.modules); + let raw_flow = data.extras().reattach(&value)?; + Ok(Arc::new(FlowData::from_raw(raw_flow)?)) + } } pub mod script { @@ -988,7 +1007,9 @@ pub mod job { (Flow, Some(id)) | (SingleStepFlow, Some(id)) => { match flow::fetch_version_lite(db, id).await { Ok(raw_flow) => Ok(raw_flow), - Err(_) => flow::fetch_version(db, id).await, + Err(_) => flow::fetch_version(db, id) + .await + .and_then(flow::as_run_version), } } _ => Err(error::Error::internal_err(format!( @@ -1343,6 +1364,24 @@ mod tests { use super::*; use serde_json::json; + #[test] + fn full_flow_version_runs_its_trailing_suspend() { + let raw = serde_json::value::to_raw_value(&json!({ + "modules": [ + {"id": "a", "value": {"type": "identity"}}, + {"id": "b", "value": {"type": "identity"}, "suspend": {"required_events": 1}} + ], + "notes": [{"id": "n"}] + })) + .unwrap(); + let run = flow::as_run_version(Arc::new(FlowData::from_raw(raw).unwrap())).unwrap(); + let ids: Vec<_> = run.value().modules.iter().map(|m| m.id.as_str()).collect(); + assert_eq!(ids, ["a", "b", "b-v"]); + assert!(run.extras().notes.is_some()); + let again = flow::as_run_version(run.clone()).unwrap(); + assert!(Arc::ptr_eq(&run, &again)); + } + #[test] fn fs_cache_put_overwrites_without_stale_tail() { // Regression for the non-truncating, non-atomic `put`: overwriting a value with a diff --git a/backend/windmill-common/src/client.rs b/backend/windmill-common/src/client.rs index 54eb486da7..b726afbcda 100644 --- a/backend/windmill-common/src/client.rs +++ b/backend/windmill-common/src/client.rs @@ -122,7 +122,9 @@ impl AuthedClient { pub async fn get_resource_value<T: DeserializeOwned>(&self, path: &str) -> anyhow::Result<T> { let url = format!( "{}/api/w/{}/resources/get_value/{}", - self.base_internal_url, self.workspace, path + self.base_internal_url, + self.workspace, + item_path_segments(path)? ); make_basic_get_request(self, &url, None, Some("decoding resource value as json")).await } @@ -138,7 +140,9 @@ impl AuthedClient { } let url = format!( "{}/api/w/{}/resources/get/{}", - self.base_internal_url, self.workspace, path + self.base_internal_url, + self.workspace, + item_path_segments(path)? ); let resource: Resource = make_basic_get_request(self, &url, None, Some("decoding the agent resource")).await?; @@ -154,7 +158,9 @@ impl AuthedClient { pub async fn get_variable_value(&self, path: &str) -> anyhow::Result<String> { let url = format!( "{}/api/w/{}/variables/get_value/{}", - self.base_internal_url, self.workspace, path + self.base_internal_url, + self.workspace, + item_path_segments(path)? ); make_basic_get_request(self, &url, None, Some("decoding variable value as json")).await } @@ -166,7 +172,9 @@ impl AuthedClient { ) -> anyhow::Result<T> { let url = format!( "{}/api/w/{}/resources/get_value_interpolated/{}", - self.base_internal_url, self.workspace, path + self.base_internal_url, + self.workspace, + item_path_segments(path)? ); let mut query = Vec::with_capacity(1usize); if let Some(v) = &job_id { @@ -422,6 +430,27 @@ mod tests { use std::time::Duration; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; + #[test] + fn item_path_stays_under_its_route() { + let route = "http://localhost/api/w/ws/variables/get_value/"; + for path in [ + "u/alice/../../jobs/run/p/u/a/b", + "u/alice/%2e%2e/x?a=1#b", + "u/a\\..\\b", + ] { + let url = item_path_segments(path) + .map(|p| reqwest::Url::parse(&format!("{route}{p}")).unwrap()); + assert!(url.map_or(true, |u| u.as_str().starts_with(route) + && u.query().is_none() + && u.fragment().is_none())); + } + assert!(item_path_segments("u/alice/../x").is_err()); + assert_eq!( + item_path_segments("f/my folder/x").unwrap(), + "f/my%20folder/x" + ); + } + async fn download_response( response: &'static str, max_bytes: Option<usize>, @@ -488,6 +517,19 @@ mod tests { } } +/// `path` as the trailing segments of an item route. Each segment is percent-encoded so it stays +/// one segment of that route, and a `.` or `..` segment is refused: the URL parser resolves it, +/// encoded or not, which would point the request at another route. +fn item_path_segments(path: &str) -> anyhow::Result<String> { + path.split('/') + .map(|segment| match segment { + "." | ".." => Err(anyhow::anyhow!("Invalid item path: {path}")), + _ => Ok(urlencoding::encode(segment)), + }) + .collect::<anyhow::Result<Vec<_>>>() + .map(|segments| segments.join("/")) +} + #[inline] fn query_from_json_path(json_path: Option<String>) -> Vec<(&'static str, String)> { json_path diff --git a/backend/windmill-common/src/client_ip.rs b/backend/windmill-common/src/client_ip.rs new file mode 100644 index 0000000000..98e0f2c7ff --- /dev/null +++ b/backend/windmill-common/src/client_ip.rs @@ -0,0 +1,1374 @@ +//! The address a request comes from. Forwarding headers are believed only when the TCP peer is a +//! trusted proxy. Then either `CLIENT_IP_HEADER` names the one header the edge in front writes +//! authoritatively, or `X-Forwarded-For` is read from the right, stopping at the first hop that is +//! not itself a trusted proxy. Everything left of that hop was written by the client and is +//! ignored. `X-Real-IP` is never read implicitly: proxies that do not set it pass the client's own +//! through. +//! +//! **Accepted risk, by design.** With `TRUSTED_PROXIES` unset, loopback and the private ranges are +//! trusted, where the ingress or reverse proxy of almost every deployment sits, so client +//! addresses, token IP allowlists included, work behind a Helm or compose install with nothing +//! configured. Any host on the private network, a job's container included, can then name its own +//! address, an allowlisted one included. That is the trade-off: a leaked IP-restricted token stays +//! restricted for an outsider, whose requests come through the ingress, not for an insider who can +//! run a job or reach the network. It is decided, not overlooked: the server warns at startup, the +//! Client IP settings page and the token dialog point to `TRUSTED_PROXIES`, which closes it when +//! it names the actual proxies rather than `private`, and audit entries keep the peer and the raw +//! header (`request_origin.rs`) so a named address is told apart. See `docs/auth-surface.md`. A finding is a change that widens it: a public range trusted +//! by default, forwarding headers believed from a peer outside the trusted list, or Cloudflare +//! reaching the enforced view. +//! +//! Two views of one request, which differ only by Cloudflare: +//! - **enforced** (`ClientIp`, `client_ip_of`): token IP allowlists. Never trusts Cloudflare. +//! - **attributed** (`attributed_client_ip`): audit entries and the login rate limit. Trusts +//! Cloudflare with `TRUST_CLOUDFLARE`. + +use std::collections::HashMap; +use std::net::{IpAddr, SocketAddr}; +use std::sync::{Arc, LazyLock, Mutex}; +use std::time::{Duration, Instant}; + +use arc_swap::ArcSwap; +use axum::extract::{ConnectInfo, FromRequestParts}; +use axum::http::{request::Parts, Extensions, HeaderMap, HeaderName}; +pub use ipnet::IpNet; +use serde::Serialize; + +const LOOPBACK: &[&str] = &["127.0.0.0/8", "::1/128"]; +const PRIVATE: &[&str] = &["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]; +/// https://www.cloudflare.com/ips-v4 and /ips-v6. Public ranges: trusted only with +/// `TRUST_CLOUDFLARE`. +const CLOUDFLARE: &[&str] = &[ + "173.245.48.0/20", + "103.21.244.0/22", + "103.22.200.0/22", + "103.31.4.0/22", + "141.101.64.0/18", + "108.162.192.0/18", + "190.93.240.0/20", + "188.114.96.0/20", + "197.234.240.0/22", + "198.41.128.0/17", + "162.158.0.0/15", + "104.16.0.0/13", + "104.24.0.0/14", + "172.64.0.0/13", + "131.0.72.0/22", + "2400:cb00::/32", + "2606:4700::/32", + "2803:f800::/32", + "2405:b500::/32", + "2405:8100::/32", + "2a06:98c0::/29", + "2c0f:f248::/32", +]; + +const HOST_REFRESH: Duration = Duration::from_secs(15); + +/// The global settings the trust is built from. Each is overridden by its environment variable +/// (`TRUSTED_PROXIES`, `TRUST_CLOUDFLARE`, `CLIENT_IP_HEADER`) when that is set. +pub const TRUSTED_PROXIES_SETTING: &str = "trusted_proxies"; +pub const TRUST_CLOUDFLARE_SETTING: &str = "trust_cloudflare"; +pub const CLIENT_IP_HEADER_SETTING: &str = "client_ip_header"; +pub const SETTING_KEYS: &[&str] = &[ + TRUSTED_PROXIES_SETTING, + TRUST_CLOUDFLARE_SETTING, + CLIENT_IP_HEADER_SETTING, +]; + +pub struct ClientIpConfig { + trusted: Vec<IpNet>, + /// Hostnames in `TRUSTED_PROXIES` (a compose service such as `caddy`), re-resolved every + /// `HOST_REFRESH` because a recreated container changes address. A name that does not + /// resolve trusts nothing. + hosts: Vec<String>, + resolved: ArcSwap<Vec<(String, Vec<IpAddr>)>>, + header: Option<HeaderName>, + cloudflare: bool, +} + +static CLOUDFLARE_NETS: LazyLock<Vec<IpNet>> = LazyLock::new(|| nets(CLOUDFLARE).collect()); + +impl ClientIpConfig { + fn new( + mut trusted: Vec<IpNet>, + hosts: Vec<String>, + cloudflare: bool, + header: Option<HeaderName>, + ) -> Self { + if cloudflare { + trusted.extend(nets(CLOUDFLARE)); + } + Self { trusted, hosts, resolved: ArcSwap::from_pointee(vec![]), header, cloudflare } + } + + /// The client behind a Cloudflare edge is the one `CF-Connecting-IP` names, and its + /// `X-Forwarded-For` is not walked further: any Cloudflare customer's Worker sends from these + /// ranges with headers of its own choosing. Cloudflare overwrites `CF-Connecting-IP` only on + /// requests to a Cloudflare zone, and a Worker calling the origin directly sets it itself, so + /// it is good for attribution only. + fn behind_cloudflare(&self, hop: IpAddr, headers: &HeaderMap) -> Option<IpAddr> { + if !self.cloudflare || !CLOUDFLARE_NETS.iter().any(|n| n.contains(&hop)) { + return None; + } + let mut values = headers.get_all("cf-connecting-ip").iter(); + Some(match (values.next(), values.next()) { + (Some(v), None) => parse_addr(v.as_bytes()).unwrap_or(hop), + _ => hop, + }) + } + + fn is_trusted(&self, ip: IpAddr) -> bool { + self.trusted.iter().any(|n| n.contains(&ip)) + || (!self.hosts.is_empty() && self.resolved.load().iter().any(|(_, a)| a.contains(&ip))) + } +} + +/// A value the trust is built from, and whether its environment variable set it, which makes +/// the setting read-only on the Client IP page. +#[derive(Serialize, Clone, Debug, PartialEq, Eq)] +pub struct Configured<T> { + pub value: T, + pub from_env: bool, +} + +#[derive(Serialize, Clone, Debug, PartialEq, Eq)] +pub struct ClientIpConfiguration { + pub trusted_proxies: Configured<Option<String>>, + pub trust_cloudflare: Configured<bool>, + pub client_ip_header: Configured<Option<String>>, +} + +pub struct ClientIpSettings { + enforced: ClientIpConfig, + /// `None` when it is the enforced view. + attributed: Option<ClientIpConfig>, + trusted_proxies_set: bool, + /// A whole private range is trusted (the default, `private`, or e.g. `10.0.0.0/8`): any host + /// on that network can then name its own client address. Listing the proxies themselves is + /// what closes it, not setting some value. + private_ranges_trusted: bool, + configuration: ClientIpConfiguration, +} + +impl ClientIpSettings { + #[cfg(test)] + fn new(trusted_proxies: Option<&str>, cloudflare: bool, header: Option<HeaderName>) -> Self { + let configuration = ClientIpConfiguration { + trusted_proxies: Configured { value: trusted_proxies.map(str::to_string), from_env: true }, + trust_cloudflare: Configured { value: cloudflare, from_env: true }, + client_ip_header: Configured { + value: header.as_ref().map(|h| h.to_string()), + from_env: true, + }, + }; + Self::build(trusted_proxies, false, cloudflare, header, configuration) + } + + /// `strict` (a stored setting rather than an environment variable) also drops the entries + /// [`validate_trusted_proxies`] refuses, should one reach the database without the check. + fn build( + trusted_proxies: Option<&str>, + strict: bool, + cloudflare: bool, + header: Option<HeaderName>, + configuration: ClientIpConfiguration, + ) -> Self { + // The accepted risk the module doc describes: never a public range here, and an explicit + // list always replaces this default rather than adding to it. + let (trusted, hosts) = match trusted_proxies { + Some(v) => { + let p = parse_trusted_proxies(v, strict); + let source = if strict { "trusted_proxies setting" } else { "TRUSTED_PROXIES" }; + for e in &p.errors { + tracing::error!("{source}: ignoring {e}"); + } + (p.trusted, p.hosts) + } + None => (nets(LOOPBACK).chain(nets(PRIVATE)).collect(), vec![]), + }; + // Cloudflare never reaches the enforced view: a Worker sending to an origin outside a + // Cloudflare zone comes from the same ranges and may set CF-Connecting-IP itself, so only + // the origin's own proof of the zone (e.g. authenticated origin pulls) could vouch for it. + let private_ranges_trusted = + nets(PRIVATE).any(|p| trusted.iter().any(|t| t.contains(&p))); + let enforced = ClientIpConfig::new(trusted.clone(), hosts.clone(), false, header.clone()); + let attributed = cloudflare.then(|| ClientIpConfig::new(trusted, hosts, true, header)); + Self { + enforced, + attributed, + trusted_proxies_set: trusted_proxies.is_some(), + private_ranges_trusted, + configuration, + } + } + + /// Each value from its environment variable when that is set, else from its global setting. + fn from_env_and_stored(stored: &Stored) -> Self { + let env = &*ENV; + let (trusted_proxies, tp_env) = match &env.trusted_proxies { + Some(v) => (Some(v.clone()), true), + None => (stored.trusted_proxies.clone(), false), + }; + let (cloudflare, cf_env) = match env.trust_cloudflare { + Some(v) => (v, true), + None => (stored.trust_cloudflare, false), + }; + let (header, h_env) = match &env.header { + Some(h) => (h.clone(), true), + None => (stored.header.clone(), false), + }; + let configuration = ClientIpConfiguration { + trusted_proxies: Configured { value: trusted_proxies.clone(), from_env: tp_env }, + trust_cloudflare: Configured { value: cloudflare, from_env: cf_env }, + client_ip_header: Configured { + value: header.as_ref().map(|h| h.to_string()), + from_env: h_env, + }, + }; + Self::build(trusted_proxies.as_deref(), !tp_env, cloudflare, header, configuration) + } + + pub fn enforced(&self) -> &ClientIpConfig { + &self.enforced + } + + pub fn attributed(&self) -> &ClientIpConfig { + self.attributed.as_ref().unwrap_or(&self.enforced) + } + + fn configs(&self) -> impl Iterator<Item = &ClientIpConfig> { + [Some(&self.enforced), self.attributed.as_ref()] + .into_iter() + .flatten() + } + + fn describe(&self) -> String { + let describe = |c: &ClientIpConfig| { + let mut parts: Vec<String> = c + .trusted + .iter() + .filter(|n| !c.cloudflare || !CLOUDFLARE_NETS.contains(n)) + .map(|n| n.to_string()) + .collect(); + parts.extend(c.hosts.iter().cloned()); + if c.cloudflare { + parts.push("Cloudflare".to_string()); + } + if parts.is_empty() { + "no proxy".to_string() + } else { + parts.join(", ") + } + }; + let header = match &self.enforced.header { + Some(h) => format!(", reading the client from {h}"), + None => String::new(), + }; + match &self.attributed { + None => format!("trusting {} as proxies{header}", describe(&self.enforced)), + Some(a) => format!( + "trusting {} as proxies for audit entries and login rate limits, {} for token IP \ + allowlists{header}", + describe(a), + describe(&self.enforced) + ), + } + } +} + +/// The environment variables, read once: they outrank the global settings for good. +struct EnvInputs { + trusted_proxies: Option<String>, + trust_cloudflare: Option<bool>, + header: Option<Option<HeaderName>>, +} + +/// `TRUSTED_PROXIES`: comma-separated IPs, CIDRs, hostnames and `private` (loopback plus the +/// private ranges); set but empty, or `none`, trusts no proxy. +/// `TRUST_CLOUDFLARE=true`: also trust Cloudflare's published ranges. +/// `CLIENT_IP_HEADER`: a header such as `CloudFront-Viewer-Address`, `CF-Connecting-IP` or +/// `X-Real-IP` that the trusted edge overwrites on every request, read instead of +/// `X-Forwarded-For`. +static ENV: LazyLock<EnvInputs> = LazyLock::new(|| EnvInputs { + trusted_proxies: std::env::var("TRUSTED_PROXIES").ok(), + trust_cloudflare: std::env::var("TRUST_CLOUDFLARE") + .ok() + .map(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "true" | "1" | "yes")), + // Set but empty or unreadable still fixes it, to X-Forwarded-For: the stored setting never + // takes over from a variable that is set. + header: std::env::var("CLIENT_IP_HEADER").ok().map(|v| { + if v.trim().is_empty() { + return None; + } + HeaderName::try_from(v.trim()) + .map_err(|_| { + tracing::error!("CLIENT_IP_HEADER: {v:?} is not a header name, ignoring it") + }) + .ok() + }), +}); + +/// The global settings' values, as stored. +#[derive(Default)] +struct Stored { + trusted_proxies: Option<String>, + trust_cloudflare: bool, + header: Option<HeaderName>, +} + +impl Stored { + fn from_values( + trusted_proxies: Option<&serde_json::Value>, + trust_cloudflare: Option<&serde_json::Value>, + header: Option<&serde_json::Value>, + ) -> Self { + let text = |v: Option<&serde_json::Value>| { + v.and_then(|v| v.as_str()) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) + }; + Stored { + trusted_proxies: text(trusted_proxies), + trust_cloudflare: trust_cloudflare.and_then(|v| v.as_bool()).unwrap_or(false), + header: text(header).and_then(|h| match parse_client_ip_header(&h) { + Ok(h) => Some(h), + Err(e) => { + tracing::error!("client_ip_header setting: {e}, ignoring it"); + None + } + }), + } + } +} + +/// Swapped whole when a setting changes ([`apply_stored`]), so a request reads one consistent +/// trust. Until the settings are first read it holds the environment variables alone. +static CLIENT_IP_SETTINGS: LazyLock<ArcSwap<ClientIpSettings>> = LazyLock::new(|| { + ArcSwap::from_pointee(ClientIpSettings::from_env_and_stored(&Stored::default())) +}); + +/// The trust in force now. +pub fn current() -> arc_swap::Guard<Arc<ClientIpSettings>> { + CLIENT_IP_SETTINGS.load() +} + +fn nets(list: &'static [&'static str]) -> impl Iterator<Item = IpNet> { + list.iter() + .map(|s| s.parse().expect("valid built-in network")) +} + +fn is_hostname(s: &str) -> bool { + s.len() <= 253 + && s.split('.').all(|l| { + !l.is_empty() + && l.len() <= 63 + && !l.starts_with('-') + && l.chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') + }) +} + +struct ParsedProxies { + trusted: Vec<IpNet>, + hosts: Vec<String>, + /// The entries left out, each with why. + errors: Vec<String>, +} + +/// `strict` also refuses what would trust far more than a proxy: every address, or a range +/// overlapping Cloudflare's, which any Cloudflare customer's Worker sends from and which +/// `TRUST_CLOUDFLARE` admits to the attributed view only. +fn parse_trusted_proxies(v: &str, strict: bool) -> ParsedProxies { + let mut p = ParsedProxies { trusted: vec![], hosts: vec![], errors: vec![] }; + if v.trim().eq_ignore_ascii_case("none") { + return p; + } + for s in v.split(',').map(str::trim).filter(|s| !s.is_empty()) { + if s.eq_ignore_ascii_case("private") { + p.trusted.extend(nets(LOOPBACK).chain(nets(PRIVATE))); + } else if let Some(net) = s + .parse::<IpNet>() + .ok() + .or_else(|| s.parse::<IpAddr>().ok().map(IpNet::from)) + { + if strict && net.prefix_len() == 0 { + p.errors.push(format!( + "{s:?}: it trusts every address, so any client could name its own" + )); + } else if let Some(cf) = strict + .then(|| { + CLOUDFLARE_NETS + .iter() + .find(|cf| cf.contains(&net.network()) || net.contains(&cf.network())) + }) + .flatten() + { + p.errors.push(format!( + "{s:?}: it overlaps Cloudflare's range {cf}, which any Cloudflare customer's \ + Worker sends from; trust Cloudflare with TRUST_CLOUDFLARE instead" + )); + } else { + p.trusted.push(net); + } + } else if strict && s.eq_ignore_ascii_case("none") { + p.errors + .push("\"none\": it trusts no proxy only on its own, not among other entries".into()); + } else if is_hostname(s) + && !(strict + && s.rsplit('.') + .next() + .is_some_and(|l| l.chars().all(|c| c.is_ascii_digit()))) + { + p.hosts.push(s.to_ascii_lowercase()); + } else { + p.errors.push(format!( + "{s:?}: not an IP address, a CIDR, a hostname or \"private\"" + )); + } + } + p +} + +/// What a write of the `trusted_proxies` setting must pass: every entry is kept, none refused. +pub fn validate_trusted_proxies(v: &str) -> Result<(), String> { + let p = parse_trusted_proxies(v, true); + if p.errors.is_empty() { + Ok(()) + } else { + Err(p.errors.join("; ")) + } +} + +fn parse_client_ip_header(v: &str) -> Result<HeaderName, String> { + let h = HeaderName::try_from(v.trim()).map_err(|_| format!("{v:?} is not a header name"))?; + // Read as one address, a multi-hop X-Forwarded-For would always fall back to the peer. + if h == "x-forwarded-for" { + return Err( + "X-Forwarded-For is read by default, from the right: leave the header empty".into(), + ); + } + Ok(h) +} + +/// Checks a write of one of [`SETTING_KEYS`]. `null` and an empty string clear the setting. +pub fn validate_setting(key: &str, value: &serde_json::Value) -> Result<(), String> { + use serde_json::Value; + match (key, value) { + (_, Value::Null) => Ok(()), + (_, Value::String(s)) if s.trim().is_empty() => Ok(()), + (TRUST_CLOUDFLARE_SETTING, Value::Bool(_)) => Ok(()), + (TRUST_CLOUDFLARE_SETTING, _) => Err("must be true or false".into()), + (TRUSTED_PROXIES_SETTING, Value::String(s)) => validate_trusted_proxies(s), + (CLIENT_IP_HEADER_SETTING, Value::String(s)) => parse_client_ip_header(s).map(|_| ()), + _ => Err("must be a string".into()), + } +} + +async fn resolve_hosts(cfg: &ClientIpConfig) { + let mut resolved = Vec::with_capacity(cfg.hosts.len()); + for host in &cfg.hosts { + let addrs = match tokio::net::lookup_host((host.as_str(), 0)).await { + Ok(a) => { + let mut a: Vec<IpAddr> = a.map(|a| canonical(a.ip())).collect(); + a.sort(); + a.dedup(); + a + } + Err(_) => vec![], + }; + let before = cfg + .resolved + .load() + .iter() + .find(|(h, _)| h == host) + .map(|(_, a)| a.clone()); + if before.as_ref() != Some(&addrs) { + if addrs.is_empty() { + tracing::warn!( + "TRUSTED_PROXIES: {host} does not resolve; no proxy is trusted under that name" + ); + } else { + tracing::info!("TRUSTED_PROXIES: {host} resolves to {addrs:?}"); + } + } + resolved.push((host.clone(), addrs)); + } + cfg.resolved.store(Arc::new(resolved)); +} + +async fn resolve_all_hosts(s: &ClientIpSettings) { + for c in s.configs().filter(|c| !c.hosts.is_empty()) { + resolve_hosts(c).await; + } +} + +static STARTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +fn warn_if_private_trusted(s: &ClientIpSettings) { + if s.private_ranges_trusted { + tracing::warn!( + "Client IP: a whole private range is trusted as proxies, so any host on the private \ + network, a Windmill job included, can name its own client address, which token IP \ + allowlists then accept. List your reverse proxies' addresses on the Client IP \ + instance settings page (or in TRUSTED_PROXIES) to trust only them." + ); + } +} + +/// Logs what the server trusts and, for hostnames in `TRUSTED_PROXIES`, resolves them before +/// the server accepts requests, then keeps those of the trust in force resolved until +/// `killpill`. +pub async fn init(mut killpill: tokio::sync::broadcast::Receiver<()>) { + if LOCAL_JOBS_ONLY.load(std::sync::atomic::Ordering::Relaxed) { + tracing::info!("Client IP: this process serves only its own jobs, no caller is a proxy"); + return; + } + let s = CLIENT_IP_SETTINGS.load_full(); + tracing::info!("Client IP: {}", s.describe()); + warn_if_private_trusted(&s); + resolve_all_hosts(&s).await; + STARTED.store(true, std::sync::atomic::Ordering::Relaxed); + tokio::spawn(async move { + loop { + tokio::select! { + _ = killpill.recv() => return, + _ = tokio::time::sleep(HOST_REFRESH) => { + resolve_all_hosts(&CLIENT_IP_SETTINGS.load_full()).await; + } + } + } + }); +} + +/// Names the stored settings an environment variable overrides, once per distinct set: the +/// settings are read again on every reload, every few seconds on an MCP server. +fn warn_if_shadowed(stored: &Stored) { + static LAST: Mutex<Vec<&'static str>> = Mutex::new(vec![]); + let env = &*ENV; + let mut shadowed = vec![]; + if env.trusted_proxies.is_some() && stored.trusted_proxies.is_some() { + shadowed.push("TRUSTED_PROXIES"); + } + if env.trust_cloudflare.is_some_and(|e| e != stored.trust_cloudflare) { + shadowed.push("TRUST_CLOUDFLARE"); + } + if env.header.is_some() && stored.header.is_some() { + shadowed.push("CLIENT_IP_HEADER"); + } + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + if *last != shadowed { + if !shadowed.is_empty() && !LOCAL_JOBS_ONLY.load(std::sync::atomic::Ordering::Relaxed) { + tracing::warn!( + "Client IP: {} set in the environment, which overrides the value stored on the \ + Client IP instance settings page", + shadowed.join(", ") + ); + } + *last = shadowed; + } +} + +/// Whether a whole private range is trusted as proxies, so that any host on the private network +/// can name its own client address. +pub fn private_ranges_trusted() -> bool { + current().private_ranges_trusted +} + +/// Rebuilds the trust from the global settings' values, as read, and swaps it in. +pub async fn apply_stored( + trusted_proxies: Option<&serde_json::Value>, + trust_cloudflare: Option<&serde_json::Value>, + client_ip_header: Option<&serde_json::Value>, +) { + let stored = Stored::from_values(trusted_proxies, trust_cloudflare, client_ip_header); + warn_if_shadowed(&stored); + let next = Arc::new(ClientIpSettings::from_env_and_stored(&stored)); + let prev = CLIENT_IP_SETTINGS.load_full(); + if prev.configuration == next.configuration { + return; + } + // A name trusted before stays trusted at its known addresses until it is re-resolved, so + // a change elsewhere in the list leaves no window in which its proxy is not believed. Both + // views resolve the same names, so the enforced one seeds a newly added attributed one too. + let known = prev.enforced.resolved.load(); + for n in next.configs() { + n.resolved.store(Arc::new( + known + .iter() + .filter(|(h, _)| n.hosts.contains(h)) + .cloned() + .collect(), + )); + } + CLIENT_IP_SETTINGS.store(next.clone()); + if LOCAL_JOBS_ONLY.load(std::sync::atomic::Ordering::Relaxed) { + return; + } + if STARTED.load(std::sync::atomic::Ordering::Relaxed) { + tracing::info!("Client IP: settings changed, now {}", next.describe()); + warn_if_private_trusted(&next); + } + if next.configs().any(|c| !c.hosts.is_empty()) { + tokio::spawn(async move { resolve_all_hosts(&next).await }); + } +} + +/// Reads the global settings and applies them: at startup, on a settings change, and on the +/// server that wrote it, right after the write. Reads and applies one reload at a time: a page +/// saves its changed keys concurrently, and a snapshot read before another key's write landed +/// must not be applied after the one read once it did. A failed read is retried, since the +/// settings change event that triggered it is not delivered again. +pub async fn reload(db: &crate::DB) { + static RELOAD: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + let _one_at_a_time = RELOAD.lock().await; + let mut wait = Duration::from_millis(500); + for attempt in 1..=4 { + match read_stored(db).await { + Ok(v) => return apply_stored(v[0].as_ref(), v[1].as_ref(), v[2].as_ref()).await, + Err(e) if attempt < 4 => { + tracing::warn!("Client IP: could not read the settings, retrying: {e:#}"); + tokio::time::sleep(wait).await; + wait *= 4; + } + Err(e) => tracing::error!( + "Client IP: could not read the settings, the trust in force is unchanged: {e:#}" + ), + } + } +} + +async fn read_stored(db: &crate::DB) -> crate::error::Result<Vec<Option<serde_json::Value>>> { + let mut values = Vec::with_capacity(SETTING_KEYS.len()); + for key in SETTING_KEYS { + values.push(crate::global_settings::load_value_from_global_settings(db, key).await?); + } + Ok(values) +} + +/// The client address of a request as token IP allowlists see it: `None` when the server was not +/// given the connection's peer (a router served without connect info, as in tests or internal +/// dispatch). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ClientIp(pub Option<IpAddr>); + +impl<S: Send + Sync> FromRequestParts<S> for ClientIp { + type Rejection = std::convert::Infallible; + + async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { + Ok(ClientIp(client_ip_of_parts(parts))) + } +} + +/// The client address as audit entries and the login rate limit see it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct AttributedClientIp(pub Option<IpAddr>); + +impl<S: Send + Sync> FromRequestParts<S> for AttributedClientIp { + type Rejection = std::convert::Infallible; + + async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { + Ok(AttributedClientIp( + peer_of(&parts.extensions).map(|p| attributed_client_ip(p, &parts.headers)), + )) + } +} + +fn peer_of(extensions: &Extensions) -> Option<IpAddr> { + extensions + .get::<ConnectInfo<SocketAddr>>() + .map(|c| c.0.ip()) +} + +pub fn client_ip_of_parts(parts: &Parts) -> Option<IpAddr> { + client_ip_of(&parts.extensions, &parts.headers) +} + +/// The same, for a handler holding the whole `Request` rather than its parts. +pub fn client_ip_of(extensions: &Extensions, headers: &HeaderMap) -> Option<IpAddr> { + let peer = peer_of(extensions)?; + Some(resolve_client_ip( + peer, + headers, + current().enforced(), + )) +} + +pub fn attributed_client_ip(peer: IpAddr, headers: &HeaderMap) -> IpAddr { + resolve_client_ip(peer, headers, current().attributed()) +} + +/// An IPv4 client of a dual-stack listener arrives as `::ffff:a.b.c.d`; compare it as IPv4 so +/// IPv4 networks match it. +pub fn canonical(ip: IpAddr) -> IpAddr { + match ip { + IpAddr::V6(v6) => v6.to_ipv4_mapped().map(IpAddr::V4).unwrap_or(ip), + v4 => v4, + } +} + +/// An address as proxies write it: bare, `ip:port` or `[v6]:port`. +fn parse_addr(bytes: &[u8]) -> Option<IpAddr> { + let s = std::str::from_utf8(bytes).ok()?.trim(); + s.parse::<IpAddr>() + .ok() + .or_else(|| s.parse::<SocketAddr>().ok().map(|a| a.ip())) + .map(canonical) +} + +/// `CloudFront-Viewer-Address` always ends in the source port, after an unbracketed IPv6 +/// address. Read generically, `2001:db8::1:4430` is itself a valid address, so each source port +/// would name a different client. +fn parse_addr_then_port(bytes: &[u8]) -> Option<IpAddr> { + let s = std::str::from_utf8(bytes).ok()?.trim(); + let (ip, port) = s.rsplit_once(':')?; + port.parse::<u16>().ok()?; + let ip = ip + .strip_prefix('[') + .and_then(|i| i.strip_suffix(']')) + .unwrap_or(ip); + ip.parse::<IpAddr>().ok().map(canonical) +} + +/// Set in a process whose API only its own jobs call: a worker, listening on loopback by default. +/// No caller there is a proxy, and loopback's trust would let a job name any address, an +/// allowlisted one included. +static LOCAL_JOBS_ONLY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +pub fn serve_local_jobs_only() { + LOCAL_JOBS_ONLY.store(true, std::sync::atomic::Ordering::Relaxed); +} + +pub fn serves_local_jobs_only() -> bool { + LOCAL_JOBS_ONLY.load(std::sync::atomic::Ordering::Relaxed) +} + +/// The trust the given stored values would put in force, environment overrides included and +/// its hostnames resolved, so a write can be checked against what it would change. +pub async fn settings_with( + trusted_proxies: Option<&serde_json::Value>, + trust_cloudflare: Option<&serde_json::Value>, + client_ip_header: Option<&serde_json::Value>, +) -> Arc<ClientIpSettings> { + let s = ClientIpSettings::from_env_and_stored(&Stored::from_values( + trusted_proxies, + trust_cloudflare, + client_ip_header, + )); + resolve_all_hosts(&s).await; + Arc::new(s) +} + +impl ClientIpSettings { + pub fn enforced_client_ip(&self, peer: &RequestPeer) -> Option<IpAddr> { + peer.peer + .map(|p| resolve_client_ip(p, &peer.headers, &self.enforced)) + } + + /// What the instance IP allowlist needs: no trusted network is a whole private block or wider + /// (the default included), since every host of a trusted network can name its own client + /// address, and when that is a private block that is the network a job runs on. + pub fn trust_is_explicit(&self) -> bool { + !self.private_ranges_trusted + } + + /// Whether `peer` sends this request on its own behalf: it is loopback or a trusted proxy and + /// carries no forwarding header this trust would read. A relayed request is never that, even + /// when its forwarding header cannot be read and its client address falls back to the peer. + pub fn is_own_request(&self, peer: IpAddr, headers: &HeaderMap) -> bool { + let forwards = match &self.enforced.header { + Some(h) => headers.contains_key(h), + None => headers.contains_key("x-forwarded-for"), + }; + let peer = canonical(peer); + !forwards && (peer.is_loopback() || self.enforced.is_trusted(peer)) + } +} + +/// A request's TCP peer and headers, for checks that resolve its client address under a trust +/// other than the one in force. +pub struct RequestPeer { + pub peer: Option<IpAddr>, + pub headers: HeaderMap, +} + +impl<S: Send + Sync> FromRequestParts<S> for RequestPeer { + type Rejection = std::convert::Infallible; + + async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { + Ok(RequestPeer { + peer: peer_of(&parts.extensions).map(canonical), + headers: parts.headers.clone(), + }) + } +} + +/// The TCP peer of a request, `None` without connect info. +pub fn peer(extensions: &Extensions) -> Option<IpAddr> { + peer_of(extensions).map(canonical) +} + +pub fn resolve_client_ip(peer: IpAddr, headers: &HeaderMap, cfg: &ClientIpConfig) -> IpAddr { + let peer = canonical(peer); + if LOCAL_JOBS_ONLY.load(std::sync::atomic::Ordering::Relaxed) || !cfg.is_trusted(peer) { + return peer; + } + if let Some(name) = &cfg.header { + let mut values = headers.get_all(name).iter(); + return match (values.next(), values.next()) { + (Some(v), None) if name.as_str() == "cloudfront-viewer-address" => { + parse_addr_then_port(v.as_bytes()).unwrap_or(peer) + } + (Some(v), None) => parse_addr(v.as_bytes()).unwrap_or(peer), + _ => peer, + }; + } + if let Some(client) = cfg.behind_cloudflare(peer, headers) { + return client; + } + // Split on raw bytes: a field that is not valid UTF-8 must stay in the list as a hop we cannot + // read, not vanish and let the fields around it shift into its place. + let hops: Vec<&[u8]> = headers + .get_all("x-forwarded-for") + .iter() + .flat_map(|v| v.as_bytes().split(|b| *b == b',')) + .collect(); + let mut client = peer; + for hop in hops.iter().rev() { + // A hop we cannot read ends what can be believed: the last trusted address stands. + let Some(ip) = parse_addr(hop) else { + return client; + }; + client = ip; + if let Some(client) = cfg.behind_cloudflare(ip, headers) { + return client; + } + if !cfg.is_trusted(ip) { + return ip; + } + } + client +} + +/// The forwarding header a request carries, as written (`CLIENT_IP_HEADER` when set, else every +/// `X-Forwarded-For` field), whether or not its peer is trusted. +pub fn forwarding_header(headers: &HeaderMap) -> Option<String> { + forwarding_header_in(headers, ¤t()) +} + +fn forwarding_header_in(headers: &HeaderMap, s: &ClientIpSettings) -> Option<String> { + let name = s + .enforced + .header + .clone() + .unwrap_or(HeaderName::from_static("x-forwarded-for")); + let values: Vec<String> = headers + .get_all(&name) + .iter() + .map(|v| String::from_utf8_lossy(v.as_bytes()).trim().to_string()) + .collect(); + (!values.is_empty()).then(|| values.join(", ")) +} + +const WARN_EVERY: Duration = Duration::from_secs(3600); +const MAX_FORWARDERS: usize = 64; +const MAX_WARNINGS_PER_HOUR: usize = 20; + +struct Seen { + last_seen: chrono::DateTime<chrono::Utc>, + last_warned: Option<Instant>, + requests: u64, +} + +#[derive(Default)] +struct Forwarders { + seen: HashMap<IpAddr, Seen>, + warnings: Vec<Instant>, +} + +static FORWARDERS: LazyLock<Mutex<Forwarders>> = LazyLock::new(Default::default); + +/// Remembers a peer that sent a forwarding header the enforced view does not believe, and warns +/// once an hour per peer when the attributed view does not believe it either: client addresses +/// are then recorded as that proxy's. +pub fn note_forwarder(peer: IpAddr, headers: &HeaderMap) { + let peer = canonical(peer); + let s = current(); + let forwarded = match &s.enforced.header { + Some(h) => headers.contains_key(h), + None => headers.contains_key("x-forwarded-for"), + }; + if !forwarded || s.enforced.is_trusted(peer) { + return; + } + let untrusted = !s.attributed().is_trusted(peer); + // Every request through a default-trusted ingress lands here: one that finds the map busy + // skips its bookkeeping rather than wait. + let mut f = match FORWARDERS.try_lock() { + Ok(f) => f, + Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => return, + }; + if !f.seen.contains_key(&peer) && f.seen.len() >= MAX_FORWARDERS { + if let Some(oldest) = f + .seen + .iter() + .min_by_key(|(_, v)| v.last_seen) + .map(|(k, _)| *k) + { + f.seen.remove(&oldest); + } + } + let now = Instant::now(); + let entry = f.seen.entry(peer).or_insert(Seen { + last_seen: chrono::Utc::now(), + last_warned: None, + requests: 0, + }); + entry.last_seen = chrono::Utc::now(); + entry.requests += 1; + if !untrusted || entry.last_warned.is_some_and(|w| now - w < WARN_EVERY) { + return; + } + entry.last_warned = Some(now); + f.warnings.retain(|w| now - *w < WARN_EVERY); + if f.warnings.len() >= MAX_WARNINGS_PER_HOUR { + return; + } + f.warnings.push(now); + tracing::warn!( + "Requests arrive with forwarding headers from {peer}, which is not in TRUSTED_PROXIES: \ + client IPs are recorded as {peer}. If it is your reverse proxy or load balancer, add it \ + to TRUSTED_PROXIES (or set TRUST_CLOUDFLARE=true behind Cloudflare). If it is not, a \ + client is sending forwarding headers of its own, which are ignored." + ); +} + +#[derive(Serialize)] +pub struct TrustView { + pub networks: Vec<String>, + pub hosts: Vec<TrustedHost>, + pub cloudflare: bool, +} + +#[derive(Serialize)] +pub struct TrustedHost { + pub name: String, + pub addresses: Vec<String>, +} + +#[derive(Serialize)] +pub struct ForwarderSeen { + pub peer: String, + /// The audit entries and login rate limit believe its forwarding headers; token IP + /// allowlists do not. + pub attributed_only: bool, + pub last_seen: chrono::DateTime<chrono::Utc>, + pub requests: u64, +} + +/// What the server believes about the request asking and the proxies it has seen. +#[derive(Serialize)] +pub struct ClientIpDiagnostics { + pub peer: Option<String>, + pub forwarding_header: Option<String>, + pub client_ip: Option<String>, + pub enforced_client_ip: Option<String>, + pub trusted_proxies_set: bool, + pub private_ranges_trusted: bool, + pub client_ip_header: Option<String>, + pub enforced: TrustView, + pub attributed: Option<TrustView>, + /// What the trust is built from, and which values the environment fixes. + pub configuration: ClientIpConfiguration, + /// On this server process only, most recent first. + pub forwarders: Vec<ForwarderSeen>, +} + +fn trust_view(c: &ClientIpConfig, cloudflare: bool) -> TrustView { + TrustView { + networks: c + .trusted + .iter() + .filter(|n| !cloudflare || !CLOUDFLARE_NETS.contains(n)) + .map(|n| n.to_string()) + .collect(), + hosts: c + .hosts + .iter() + .map(|h| TrustedHost { + name: h.clone(), + addresses: c + .resolved + .load() + .iter() + .find(|(n, _)| n == h) + .map(|(_, a)| a.iter().map(|a| a.to_string()).collect()) + .unwrap_or_default(), + }) + .collect(), + cloudflare, + } +} + +pub fn diagnose(extensions: &Extensions, headers: &HeaderMap) -> ClientIpDiagnostics { + let s = current(); + let peer = peer_of(extensions).map(canonical); + let s_ip = |c: &ClientIpConfig| peer.map(|p| resolve_client_ip(p, headers, c).to_string()); + let mut forwarders: Vec<ForwarderSeen> = { + let f = FORWARDERS.lock().unwrap_or_else(|e| e.into_inner()); + f.seen + .iter() + .filter(|(p, _)| !s.enforced.is_trusted(**p)) + .map(|(p, v)| ForwarderSeen { + peer: p.to_string(), + attributed_only: s.attributed().is_trusted(*p), + last_seen: v.last_seen, + requests: v.requests, + }) + .collect() + }; + forwarders.sort_by(|a, b| b.last_seen.cmp(&a.last_seen)); + ClientIpDiagnostics { + peer: peer.map(|p| p.to_string()), + forwarding_header: forwarding_header_in(headers, &s), + client_ip: s_ip(s.attributed()), + enforced_client_ip: s_ip(&s.enforced), + trusted_proxies_set: s.trusted_proxies_set, + private_ranges_trusted: s.private_ranges_trusted, + client_ip_header: s.enforced.header.as_ref().map(|h| h.to_string()), + enforced: trust_view(&s.enforced, s.enforced.cloudflare), + attributed: s + .attributed + .as_ref() + .map(|a| trust_view(a, a.cloudflare)), + configuration: s.configuration.clone(), + forwarders, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use axum::http::HeaderValue; + + fn headers(pairs: &[(&'static str, &[u8])]) -> HeaderMap { + let mut h = HeaderMap::new(); + for (k, v) in pairs { + h.append(*k, HeaderValue::from_bytes(v).unwrap()); + } + h + } + + fn ip(s: &str) -> IpAddr { + s.parse().unwrap() + } + + fn cfg(trusted: &str, header: Option<&'static str>) -> ClientIpConfig { + let p = parse_trusted_proxies(trusted, false); + ClientIpConfig::new(p.trusted, p.hosts, false, header.map(HeaderName::from_static)) + } + + /// `TRUSTED_PROXIES` unset on a self-hosted instance. + fn unset(cloudflare: bool) -> ClientIpSettings { + ClientIpSettings::new(None, cloudflare, None) + } + + fn defaults() -> ClientIpConfig { + cfg("private", None) + } + + #[test] + fn default_trusts_loopback_and_private_proxies() { + let s = unset(false); + let h = headers(&[("x-forwarded-for", b"5.5.5.5")]); + for peer in ["10.0.0.1", "172.18.0.4", "192.168.1.2", "127.0.0.1", "fd00::1"] { + assert_eq!(resolve_client_ip(ip(peer), &h, s.enforced()), ip("5.5.5.5")); + } + assert_eq!(resolve_client_ip(ip("100.64.0.1"), &h, s.enforced()), ip("100.64.0.1")); + } + + #[test] + fn public_peer_is_the_client() { + let s = unset(false); + let h = headers(&[("x-forwarded-for", b"10.0.0.9")]); + for c in [s.attributed(), s.enforced()] { + assert_eq!(resolve_client_ip(ip("1.2.3.4"), &h, c), ip("1.2.3.4")); + } + let c = cfg("10.0.0.0/8", Some("cf-connecting-ip")); + let h = headers(&[("cf-connecting-ip", b"5.5.5.5")]); + assert_eq!(resolve_client_ip(ip("1.2.3.4"), &h, &c), ip("1.2.3.4")); + } + + #[test] + fn prepended_addresses_are_not_believed() { + let s = unset(false); + // Straight from the client: the peer. + let h = headers(&[("x-forwarded-for", b"1.2.3.4, 5.5.5.5")]); + assert_eq!( + resolve_client_ip(ip("5.5.5.5"), &h, s.attributed()), + ip("5.5.5.5") + ); + // Through a trusted proxy, which appended the real address: that address. + assert_eq!( + resolve_client_ip(ip("10.0.0.1"), &h, s.attributed()), + ip("5.5.5.5") + ); + } + + #[test] + fn cloudflare_in_front_of_a_private_load_balancer() { + let h = headers(&[ + ("x-forwarded-for", b"6.6.6.6, 5.5.5.5, 162.158.1.1"), + ("cf-connecting-ip", b"5.5.5.5"), + ]); + let s = unset(false); + assert_eq!( + resolve_client_ip(ip("10.0.0.1"), &h, s.attributed()), + ip("162.158.1.1") + ); + for s in [unset(true), ClientIpSettings::new(Some("10.0.0.0/8"), true, None)] { + assert_eq!( + resolve_client_ip(ip("10.0.0.1"), &h, s.attributed()), + ip("5.5.5.5") + ); + // Cloudflare straight to the server. + assert_eq!( + resolve_client_ip(ip("162.158.1.1"), &h, s.attributed()), + ip("5.5.5.5") + ); + // Any Worker can send from these ranges with a CF-Connecting-IP of its choosing: an + // allowlist sees the edge. + assert_eq!( + resolve_client_ip(ip("162.158.1.1"), &h, s.enforced()), + ip("162.158.1.1") + ); + } + // A Worker's subrequest to a Cloudflare zone: it writes X-Forwarded-For, Cloudflare + // writes CF-Connecting-IP. + let s = unset(true); + let h = headers(&[ + ("x-forwarded-for", b"5.5.5.5, 162.158.1.1"), + ("cf-connecting-ip", b"2a06:98c0:3600::103"), + ]); + assert_eq!( + resolve_client_ip(ip("10.0.0.1"), &h, s.attributed()), + ip("2a06:98c0:3600::103") + ); + // Without it, the edge itself. + let h = headers(&[("x-forwarded-for", b"5.5.5.5, 162.158.1.1")]); + assert_eq!( + resolve_client_ip(ip("10.0.0.1"), &h, s.attributed()), + ip("162.158.1.1") + ); + } + + #[test] + fn explicit_trusted_proxies_set_both_views() { + let h = headers(&[("x-forwarded-for", b"5.5.5.5")]); + for v in ["none", ""] { + let s = ClientIpSettings::new(Some(v), false, None); + for c in [s.attributed(), s.enforced()] { + assert_eq!(resolve_client_ip(ip("127.0.0.1"), &h, c), ip("127.0.0.1")); + assert_eq!(resolve_client_ip(ip("10.0.0.1"), &h, c), ip("10.0.0.1")); + } + } + let s = ClientIpSettings::new(Some("10.1.0.0/16"), false, None); + for c in [s.attributed(), s.enforced()] { + assert_eq!(resolve_client_ip(ip("10.1.0.1"), &h, c), ip("5.5.5.5")); + assert_eq!(resolve_client_ip(ip("10.2.0.1"), &h, c), ip("10.2.0.1")); + } + } + + #[test] + fn hostnames_trust_what_they_resolve_to() { + let c = cfg("caddy, 10.1.0.0/16", None); + assert_eq!(c.hosts, vec!["caddy".to_string()]); + let h = headers(&[("x-forwarded-for", b"5.5.5.5")]); + assert_eq!( + resolve_client_ip(ip("172.18.0.4"), &h, &c), + ip("172.18.0.4") + ); + c.resolved.store(Arc::new(vec![( + "caddy".to_string(), + vec![ip("172.18.0.4")], + )])); + assert_eq!(resolve_client_ip(ip("172.18.0.4"), &h, &c), ip("5.5.5.5")); + assert_eq!( + resolve_client_ip(ip("172.18.0.5"), &h, &c), + ip("172.18.0.5") + ); + assert!(cfg("not a host!", None).hosts.is_empty()); + } + + #[test] + fn forwarded_for_is_read_from_the_right() { + // A client-written leftmost entry is skipped: the proxy appended the real address. + let h = headers(&[("x-forwarded-for", b"6.6.6.6, 5.5.5.5, 10.0.0.2")]); + assert_eq!( + resolve_client_ip(ip("10.0.0.1"), &h, &defaults()), + ip("5.5.5.5") + ); + let h = headers(&[ + ("x-forwarded-for", b"6.6.6.6"), + ("x-forwarded-for", b"5.5.5.5"), + ]); + assert_eq!( + resolve_client_ip(ip("10.0.0.1"), &h, &defaults()), + ip("5.5.5.5") + ); + } + + #[test] + fn real_ip_is_not_read_implicitly() { + let h = headers(&[("x-real-ip", b"5.5.5.5")]); + assert_eq!( + resolve_client_ip(ip("10.0.0.1"), &h, &defaults()), + ip("10.0.0.1") + ); + } + + #[test] + fn unreadable_hop_stops_at_the_last_trusted_address() { + let h = headers(&[("x-forwarded-for", b"5.5.5.5, garbage, 10.0.0.2")]); + assert_eq!( + resolve_client_ip(ip("10.0.0.1"), &h, &defaults()), + ip("10.0.0.2") + ); + // A non-UTF-8 field is a hop too, not a field to drop. + let h = headers(&[ + ("x-forwarded-for", b"6.6.6.6"), + ("x-forwarded-for", b"\x80, 10.0.0.2"), + ]); + assert_eq!( + resolve_client_ip(ip("10.0.0.1"), &h, &defaults()), + ip("10.0.0.2") + ); + } + + #[test] + fn a_configured_cdn_range_is_walked_through() { + let c = cfg("10.0.0.0/8, 130.176.0.0/16", None); + let h = headers(&[("x-forwarded-for", b"5.5.5.5, 130.176.1.1")]); + assert_eq!(resolve_client_ip(ip("10.0.0.1"), &h, &c), ip("5.5.5.5")); + assert_eq!( + resolve_client_ip(ip("10.0.0.1"), &h, &defaults()), + ip("130.176.1.1") + ); + } + + #[test] + fn configured_header_replaces_forwarded_for() { + let c = cfg("10.0.0.0/8", Some("cloudfront-viewer-address")); + let h = headers(&[ + ("x-forwarded-for", b"6.6.6.6"), + ( + "cloudfront-viewer-address", + b"2001:0db8:85a3:0000:0000:8a2e:0370:7334:46532", + ), + ]); + assert_eq!( + resolve_client_ip(ip("10.0.0.1"), &h, &c), + ip("2001:db8:85a3::8a2e:370:7334") + ); + let h = headers(&[("cloudfront-viewer-address", b"5.5.5.5:443")]); + assert_eq!(resolve_client_ip(ip("10.0.0.1"), &h, &c), ip("5.5.5.5")); + // Compressed IPv6 with a short port also parses as a bare address: the port must go. + for port in ["4430", "4431"] { + let v = format!("2001:db8::1:{port}"); + let h = headers(&[("cloudfront-viewer-address", v.as_bytes())]); + assert_eq!(resolve_client_ip(ip("10.0.0.1"), &h, &c), ip("2001:db8::1")); + } + // Absent, repeated or unreadable: the peer, never a guess. + let h = headers(&[("x-forwarded-for", b"6.6.6.6")]); + assert_eq!(resolve_client_ip(ip("10.0.0.1"), &h, &c), ip("10.0.0.1")); + let h = headers(&[ + ("cloudfront-viewer-address", b"5.5.5.5:1"), + ("cloudfront-viewer-address", b"6.6.6.6:1"), + ]); + assert_eq!(resolve_client_ip(ip("10.0.0.1"), &h, &c), ip("10.0.0.1")); + } + + #[test] + fn stored_trusted_proxies_refuse_what_is_not_a_proxy() { + assert!(validate_trusted_proxies("private, 10.1.2.3, 172.20.0.0/16, caddy, fd00::/8").is_ok()); + assert!(validate_trusted_proxies("none").is_ok()); + for bad in [ + "0.0.0.0/0", + "::/0", + "10.0.0.0/8, 104.16.0.0/12", + "162.158.1.1", + "2606:4700::/48", + "10.0.0.0/33", + "10.0.0.256", + "none, 10.0.0.1", + "not a host!", + ] { + assert!(validate_trusted_proxies(bad).is_err(), "{bad} accepted"); + } + // Refused entries never reach the trust, even from a value that skipped the check. + let p = parse_trusted_proxies("0.0.0.0/0, 104.16.0.0/12, 10.0.0.1", true); + assert_eq!(p.trusted, vec!["10.0.0.1/32".parse::<IpNet>().unwrap()]); + assert_eq!(p.errors.len(), 2); + } + + #[tokio::test] + async fn explicit_trust_names_no_whole_private_block() { + let t = |v: Option<&'static str>| async move { + settings_with(v.map(serde_json::Value::from).as_ref(), None, None) + .await + .trust_is_explicit() + }; + assert!(t(Some("10.1.2.3")).await); + assert!(t(Some("10.244.0.0/16")).await); + for broad in [ + None, + Some("private"), + Some("10.0.0.0/8"), + Some("10.0.0.0/7"), + Some("10.0.0.0/8,172.16.0.0/12,192.168.0.0/16"), + ] { + assert!(!t(broad).await, "{broad:?}"); + } + } + + #[tokio::test] + async fn a_swap_keeps_resolved_hosts_and_takes_effect() { + let v = |s: &str| serde_json::Value::String(s.to_string()); + let h = headers(&[("x-forwarded-for", b"5.5.5.5")]); + apply_stored(Some(&v("caddy, 10.1.0.0/16")), None, None).await; + assert_eq!(resolve_client_ip(ip("10.1.0.1"), &h, current().enforced()), ip("5.5.5.5")); + assert_eq!(resolve_client_ip(ip("10.2.0.1"), &h, current().enforced()), ip("10.2.0.1")); + current() + .enforced() + .resolved + .store(Arc::new(vec![("caddy".to_string(), vec![ip("172.18.0.4")])])); + apply_stored(Some(&v("caddy, 10.2.0.0/16")), None, None).await; + let s = current(); + assert_eq!(resolve_client_ip(ip("172.18.0.4"), &h, s.enforced()), ip("5.5.5.5")); + assert_eq!(resolve_client_ip(ip("10.1.0.1"), &h, s.enforced()), ip("10.1.0.1")); + assert_eq!(resolve_client_ip(ip("10.2.0.1"), &h, s.enforced()), ip("5.5.5.5")); + assert!(!s.configuration.trusted_proxies.from_env); + assert!(!s.private_ranges_trusted); + // Set, but still trusting every private host: the exposure, not the value, is what counts. + apply_stored(Some(&v("private, 1.2.3.4")), None, None).await; + assert!(current().private_ranges_trusted); + apply_stored(None, None, None).await; + assert!(!current().trusted_proxies_set); + assert!(current().private_ranges_trusted); + } + + #[test] + fn mapped_v4_is_v4() { + assert_eq!( + resolve_client_ip(ip("::ffff:1.2.3.4"), &HeaderMap::new(), &defaults()), + ip("1.2.3.4") + ); + let h = headers(&[("x-forwarded-for", b"5.5.5.5")]); + assert_eq!( + resolve_client_ip(ip("::ffff:10.0.0.1"), &h, &defaults()), + ip("5.5.5.5") + ); + } +} diff --git a/backend/windmill-common/src/error.rs b/backend/windmill-common/src/error.rs index dd8ec49f92..80f1fdacfb 100644 --- a/backend/windmill-common/src/error.rs +++ b/backend/windmill-common/src/error.rs @@ -328,11 +328,17 @@ impl IntoResponse for Error { axum::response::Response::builder() .header("Content-Type", "text/plain") .status(status) + .extension(ServerError) .body(body) .unwrap() } } +/// Marks a response rendered from an [`Error`], so a layer can tell Windmill's own refusals +/// from a body a job chose, such as a sync run's custom status and content type. +#[derive(Clone, Copy, Debug)] +pub struct ServerError; + /// Render a `JsonErr` payload as a readable message suitable for direct /// display in a toast: surface the `error` field as the headline, append a /// short summary of `details` (e.g. duplicate paths) when present, and fall diff --git a/backend/windmill-common/src/external_instance_pg.rs b/backend/windmill-common/src/external_instance_pg.rs index 72920a1874..855bde31c2 100644 --- a/backend/windmill-common/src/external_instance_pg.rs +++ b/backend/windmill-common/src/external_instance_pg.rs @@ -262,7 +262,7 @@ pub async fn external_instance_connection_unchecked( } /// Create `dbname` on the external cluster and register it. Refuses a name already taken there, -/// whoever took it. +/// whoever took it. `extensions` are created in it first, as [`crate::provision_extensions`] does. /// /// Runs on `tx`, which it takes [`lock_external_instance_pg_state`] on: the registration lands when /// the caller commits. Take that lock before any database governance lock, as saves do. @@ -275,6 +275,7 @@ pub async fn create_external_instance_database_unchecked( dbname: &str, tag: &str, for_workspace: Option<&str>, + extensions: &[crate::DatabaseExtension], ) -> Result<()> { crate::external_instance_pg_oss::create_external_instance_database_unchecked( db, @@ -282,6 +283,7 @@ pub async fn create_external_instance_database_unchecked( dbname, tag, for_workspace, + extensions, ) .await } diff --git a/backend/windmill-common/src/external_instance_pg_oss.rs b/backend/windmill-common/src/external_instance_pg_oss.rs index 93b6fc63dd..f1683e13dd 100644 --- a/backend/windmill-common/src/external_instance_pg_oss.rs +++ b/backend/windmill-common/src/external_instance_pg_oss.rs @@ -68,6 +68,7 @@ mod ce { _dbname: &str, _tag: &str, _for_workspace: Option<&str>, + _extensions: &[crate::DatabaseExtension], ) -> Result<()> { Err(unavailable()) } diff --git a/backend/windmill-common/src/global_settings.rs b/backend/windmill-common/src/global_settings.rs index e87dd17a76..23d5d5e6a0 100644 --- a/backend/windmill-common/src/global_settings.rs +++ b/backend/windmill-common/src/global_settings.rs @@ -47,6 +47,7 @@ pub const MAVEN_REPOS_SETTING: &str = "maven_repos"; pub const MAVEN_SETTINGS_XML_SETTING: &str = "maven_settings_xml"; pub const NO_DEFAULT_MAVEN_SETTING: &str = "no_default_maven"; pub const RUBY_REPOS_SETTING: &str = "ruby_repos"; +pub const CRAN_REPO_URL_SETTING: &str = "cran_repo_url"; pub const CARGO_REGISTRIES_SETTING: &str = "cargo_registries"; pub const EXTRA_PIP_INDEX_URL_SETTING: &str = "pip_extra_index_url"; @@ -109,6 +110,7 @@ pub const HUB_API_SECRET_SETTING: &str = "hub_api_secret"; pub const AUTOMATE_USERNAME_CREATION_SETTING: &str = "automate_username_creation"; pub const DISABLE_WORKSPACE_INVITE_EMAILS_SETTING: &str = "disable_workspace_invite_emails"; pub const DISABLE_PASSWORD_LOGIN_SETTING: &str = "disable_password_login"; +pub const REQUIRE_TOTP_SETTING: &str = "require_totp"; /// Refuse `?token=` on the MCP endpoints, leaving the `Authorization` header as the only way /// in. A URL-borne credential ends up in browser history, proxy logs and referrers, so an /// instance that cares sends MCP clients through the OAuth flow instead. @@ -116,6 +118,7 @@ pub const MCP_DISABLE_TOKEN_QUERY_PARAM_SETTING: &str = "mcp_disable_token_query /// An external OIDC issuer whose access tokens the MCP endpoints accept, and the OAuth clients /// of that issuer they serve. Read and validated by [`parse_mcp_external_idp`]. pub const MCP_EXTERNAL_IDP_SETTING: &str = "mcp_external_idp"; +pub const INSTANCE_IP_ALLOWLIST_SETTING: &str = "instance_ip_allowlist"; /// Ceiling, in days, on how far ahead a token minted through `POST /users/tokens/create` or /// `POST /users/tokens/impersonate` may expire; a request asking for more, or for no /// expiration at all, is shortened to it rather than refused. On those routes only: server-side @@ -584,6 +587,7 @@ use std::sync::atomic::AtomicBool; lazy_static::lazy_static! { pub static ref HTTP_ROUTE_WORKSPACED_ROUTE: AtomicBool = AtomicBool::new(false); pub static ref DISABLE_PASSWORD_LOGIN: AtomicBool = AtomicBool::new(false); + pub static ref REQUIRE_TOTP: AtomicBool = AtomicBool::new(false); pub static ref MCP_DISABLE_TOKEN_QUERY_PARAM: AtomicBool = AtomicBool::new(false); /// `None` when [`MCP_EXTERNAL_IDP_SETTING`] is unset or has no issuer. pub static ref MCP_EXTERNAL_IDP: arc_swap::ArcSwapOption<McpExternalIdp> = @@ -924,6 +928,9 @@ pub const ENV_SETTINGS: &[&str] = &[ "WORKER_GROUP", "SAML_METADATA", "INSTANCE_IS_DEV", + "TRUSTED_PROXIES", + "TRUST_CLOUDFLARE", + "CLIENT_IP_HEADER", "OTEL_METRICS", "OTEL_TRACING", "OTEL_LOGS", @@ -932,6 +939,12 @@ pub const ENV_SETTINGS: &[&str] = &[ "OTEL_METRICS_ENABLED", "OTEL_TRACING_ENABLED", "OTEL_LOGS_ENABLED", + "OTEL_LOGS_EXCLUDE_AUDIT", + // OTEL_AUDIT_LOGS_HEADERS is left out for the same reason as the exporter headers above. + "OTEL_AUDIT_LOGS_ENABLED", + "OTEL_AUDIT_LOGS_ENDPOINT", + "OTEL_AUDIT_LOGS_PROTOCOL", + "OTEL_AUDIT_LOGS_WORKSPACES", "OTEL_EXPORTER_OTLP_ENDPOINT", "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT", diff --git a/backend/windmill-common/src/instance_config.rs b/backend/windmill-common/src/instance_config.rs index 1e92fe6372..d0923a08c6 100644 --- a/backend/windmill-common/src/instance_config.rs +++ b/backend/windmill-common/src/instance_config.rs @@ -276,6 +276,8 @@ pub struct GlobalSettings { pub auto_build_binary_on_deploy: Option<bool>, #[serde(skip_serializing_if = "Option::is_none")] pub ai_sessions_instance_storage_fallback: Option<bool>, + #[serde(skip_serializing_if = "Option::is_none")] + pub trust_cloudflare: Option<bool>, // String settings #[serde(skip_serializing_if = "Option::is_none")] @@ -293,6 +295,10 @@ pub struct GlobalSettings { #[serde(skip_serializing_if = "Option::is_none")] pub api_base_url_applies_to: Option<Vec<String>>, #[serde(skip_serializing_if = "Option::is_none")] + pub trusted_proxies: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub client_ip_header: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] pub email_domain: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub hub_base_url: Option<String>, @@ -333,6 +339,8 @@ pub struct GlobalSettings { #[serde(skip_serializing_if = "Option::is_none")] pub ruby_repos: Option<StringOrSecretRef>, #[serde(skip_serializing_if = "Option::is_none")] + pub cran_repo_url: Option<StringOrSecretRef>, + #[serde(skip_serializing_if = "Option::is_none")] pub powershell_repo_url: Option<StringOrSecretRef>, #[serde(skip_serializing_if = "Option::is_none")] pub powershell_repo_pat: Option<StringOrSecretRef>, @@ -590,8 +598,6 @@ pub struct OAuthClient { pub login_config: Option<OAuthConfig>, #[serde(skip_serializing_if = "Option::is_none")] pub tenant: Option<String>, - #[serde(skip_serializing_if = "Option::is_none")] - pub share_with_workspaces: Option<bool>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub grant_types: Vec<String>, #[serde(skip_serializing_if = "Option::is_none")] @@ -649,6 +655,21 @@ pub struct OtelSettings { pub metrics_enabled: Option<bool>, #[serde(skip_serializing_if = "Option::is_none")] pub logs_enabled: Option<bool>, + /// Leave audit events out of the logs export. + #[serde(skip_serializing_if = "Option::is_none")] + pub logs_exclude_audit: Option<bool>, + /// A second logs exporter that receives audit events only. + #[serde(skip_serializing_if = "Option::is_none")] + pub audit_logs_enabled: Option<bool>, + #[serde(skip_serializing_if = "Option::is_none")] + pub audit_logs_endpoint: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub audit_logs_headers: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub audit_logs_protocol: Option<String>, + /// Restrict the audit export to these workspaces; instance-level entries are always kept. + #[serde(skip_serializing_if = "Option::is_none")] + pub audit_logs_workspaces: Option<Vec<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub tracing_enabled: Option<bool>, #[serde(skip_serializing_if = "Option::is_none")] @@ -1197,9 +1218,15 @@ const SENSITIVE_SETTINGS: &[&str] = &[ "npmrc", "maven_repos", "ruby_repos", + "cran_repo_url", "powershell_repo_pat", "workspace_registries", "sandbox_registry_auth", + "nuget_config", + "maven_settings_xml", + "cargo_registries", + // A webhook URL is commonly its own credential. + "instance_events_webhook", ]; /// Object-valued settings that contain sensitive sub-fields. @@ -1224,8 +1251,55 @@ const NESTED_SENSITIVE_FIELDS: &[(&str, &[&str])] = &[ ("custom_instance_pg_databases", &["user_pwd"]), ("external_instance_pg", &["password"]), ("github_enterprise_app", &["private_key"]), + ( + "otel", + &["otel_exporter_otlp_headers", "audit_logs_headers"], + ), ]; +/// Settings that are maps-of-objects where each child has sensitive sub-fields. +const NESTED_MAP_SENSITIVE: &[(&str, &[&str])] = &[ + ("oauths", &["secret", "signing_secret"]), + ("external_secrets", &["token", "approle_secret_id"]), +]; + +/// Calls `f` on every part of setting `key`'s value that holds a secret, as listed in +/// [`SENSITIVE_SETTINGS`], [`NESTED_SENSITIVE_FIELDS`] and [`NESTED_MAP_SENSITIVE`]. Logs +/// and API reads both redact through it, so a new secret is listed once, there. +fn visit_secrets( + key: &str, + value: &mut serde_json::Value, + f: &mut dyn FnMut(&mut serde_json::Value), +) { + if SENSITIVE_SETTINGS.contains(&key) { + f(value); + return; + } + if let Some((_, fields)) = NESTED_SENSITIVE_FIELDS.iter().find(|(k, _)| *k == key) { + if let Some(obj) = value.as_object_mut() { + for field in *fields { + if let Some(v) = obj.get_mut(*field) { + f(v); + } + } + } + return; + } + if let Some((_, fields)) = NESTED_MAP_SENSITIVE.iter().find(|(k, _)| *k == key) { + if let Some(entries) = value.as_object_mut() { + for entry in entries.values_mut() { + if let Some(obj) = entry.as_object_mut() { + for field in *fields { + if let Some(v) = obj.get_mut(*field) { + f(v); + } + } + } + } + } + } +} + fn redact_json_value(value: &serde_json::Value) -> serde_json::Value { match value { serde_json::Value::String(s) => serde_json::json!(redact_string(s)), @@ -1234,42 +1308,89 @@ fn redact_json_value(value: &serde_json::Value) -> serde_json::Value { } fn mask_nested_sensitive(key: &str, value: &serde_json::Value) -> serde_json::Value { - for &(parent_key, sub_fields) in NESTED_SENSITIVE_FIELDS { - if key == parent_key { - if let serde_json::Value::Object(map) = value { - let mut masked = map.clone(); - for &field in sub_fields { - if let Some(v) = masked.get(field) { - masked.insert(field.to_string(), redact_json_value(v)); - } - } - return serde_json::Value::Object(masked); - } + let mut masked = value.clone(); + visit_secrets(key, &mut masked, &mut |v| *v = redact_json_value(v)); + masked +} + +/// What the settings read endpoints return in place of a stored secret unless the caller +/// passes `dangerously_reveal_secrets=true`. A write carrying it back keeps the stored value +/// at that spot ([`restore_redacted_secrets`]), so a redacted read round-trips through a write. +pub const REDACTED_SECRET: &str = + "__REDACTED__ (read it with dangerously_reveal_secrets=true; send this back unchanged to keep the stored value)"; + +/// Replaces every secret in setting `key`'s value with [`REDACTED_SECRET`]. Only non-empty +/// strings are replaced, recursing into objects and arrays, so the value keeps the shape its +/// typed config field parses, and an unset secret still reads as unset. +pub fn redact_setting_secrets(key: &str, value: &mut serde_json::Value) { + fn redact_leaves(v: &mut serde_json::Value) { + match v { + serde_json::Value::String(s) if !s.is_empty() => *s = REDACTED_SECRET.to_string(), + serde_json::Value::Array(items) => items.iter_mut().for_each(redact_leaves), + serde_json::Value::Object(obj) => obj.values_mut().for_each(redact_leaves), + _ => {} } } - // Settings that are maps-of-objects where each child has a sensitive sub-field. - const NESTED_MAP_SENSITIVE: &[(&str, &[&str])] = &[ - ("oauths", &["secret", "signing_secret"]), - ("external_secrets", &["token", "approle_secret_id"]), - ]; - for &(parent_key, child_fields) in NESTED_MAP_SENSITIVE { - if key == parent_key { - if let serde_json::Value::Object(entries) = value { - let mut masked = entries.clone(); - for (_entry_key, entry_val) in masked.iter_mut() { - if let serde_json::Value::Object(ref mut obj) = entry_val { - for &child_field in child_fields { - if let Some(v) = obj.get(child_field) { - obj.insert(child_field.to_string(), redact_json_value(v)); - } - } - } + visit_secrets(key, value, &mut redact_leaves); +} + +pub fn contains_redacted_secret(value: &serde_json::Value) -> bool { + match value { + serde_json::Value::String(s) => s == REDACTED_SECRET, + serde_json::Value::Array(items) => items.iter().any(contains_redacted_secret), + serde_json::Value::Object(obj) => obj.values().any(contains_redacted_secret), + _ => false, + } +} + +/// Puts the stored value back wherever `desired` carries [`REDACTED_SECRET`], matched by JSON +/// path against `current`. Fails rather than store the placeholder when nothing is stored there. +pub fn restore_redacted_secrets( + key: &str, + desired: &mut serde_json::Value, + current: Option<&serde_json::Value>, +) -> Result<(), String> { + fn walk( + path: &mut String, + desired: &mut serde_json::Value, + current: Option<&serde_json::Value>, + ) -> Result<(), String> { + match desired { + serde_json::Value::String(s) if s == REDACTED_SECRET => match current { + Some(c) if !c.is_null() => { + *desired = c.clone(); + Ok(()) } - return serde_json::Value::Object(masked); + _ => Err(format!( + "{path} is the redacted placeholder, but no value is stored there to keep" + )), + }, + serde_json::Value::Object(obj) => { + for (k, v) in obj.iter_mut() { + let len = path.len(); + path.push('.'); + path.push_str(k); + walk(path, v, current.and_then(|c| c.get(k.as_str())))?; + path.truncate(len); + } + Ok(()) } + serde_json::Value::Array(items) => { + for (i, v) in items.iter_mut().enumerate() { + let len = path.len(); + path.push_str(&format!("[{i}]")); + walk(path, v, current.and_then(|c| c.get(i)))?; + path.truncate(len); + } + Ok(()) + } + _ => Ok(()), } } - value.clone() + if !contains_redacted_secret(desired) { + return Ok(()); + } + walk(&mut key.to_string(), desired, current) } fn redact_string(s: &str) -> String { @@ -1518,6 +1639,15 @@ pub async fn sync_global_settings_declarative( desired: &BTreeMap<String, serde_json::Value>, observer: &impl ConfigWriteObserver, ) -> anyhow::Result<()> { + let mut restored = None; + if desired.values().any(contains_redacted_secret) { + let mut copy = desired.clone(); + for (key, value) in copy.iter_mut() { + restore_redacted_secrets(key, value, current.get(key)).map_err(anyhow::Error::msg)?; + } + restored = Some(copy); + } + let desired = restored.as_ref().unwrap_or(desired); for url_key in [ crate::global_settings::GITHUB_APP_WEBHOOK_BASE_URL_SETTING, crate::global_settings::API_BASE_URL_SETTING, @@ -1618,6 +1748,15 @@ pub async fn sync_global_settings_declarative( .await .map_err(|e| anyhow::anyhow!("{roles_key}: {e}"))?; } + // No request here to check a lockout against: a list written from config is the + // operator's to keep reachable. + let ip_allowlist_written = crate::instance_ip_allowlist::take_concerned(&mut diff); + crate::instance_ip_allowlist::write_checked(db, &ip_allowlist_written, None) + .await + .map_err(|e| anyhow::anyhow!("{e}"))?; + for (key, value) in &ip_allowlist_written { + observer.setting_written(key, value.as_ref()).await?; + } crate::external_instance_pg::write_external_instance_pg_from_diff(db, &mut diff, observer) .await?; apply_settings_diff(db, &diff, observer).await?; @@ -1786,20 +1925,24 @@ pub fn resolve_env_refs(settings: &mut GlobalSettings) -> Result<(), String> { impl InstanceConfig { /// Read the full instance configuration from the database. pub async fn from_db(db: &sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<Self> { - Self::read_from_db(db, true).await + Self::read_from_db(db, true, true).await } /// The instance configuration as an API response may carry it: `from_db` without - /// `SERVER_SECRET_SETTINGS` unless `server_secrets_exported()`. It holds admin-entered - /// credentials (`license_key`, `scim_token`, SMTP and OAuth secrets), so callers must - /// have checked superadmin. - pub async fn from_db_for_api(db: &sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<Self> { - Self::read_from_db(db, server_secrets_exported()).await + /// `SERVER_SECRET_SETTINGS` unless `server_secrets_exported()`, and with every secret + /// replaced by [`REDACTED_SECRET`] unless `reveal_secrets`. Callers must have checked + /// superadmin. + pub async fn from_db_for_api( + db: &sqlx::Pool<sqlx::Postgres>, + reveal_secrets: bool, + ) -> anyhow::Result<Self> { + Self::read_from_db(db, server_secrets_exported(), reveal_secrets).await } async fn read_from_db( db: &sqlx::Pool<sqlx::Postgres>, include_server_secrets: bool, + reveal_secrets: bool, ) -> anyhow::Result<Self> { // Read global_settings table → flat map → deserialize into GlobalSettings let rows: Vec<(String, serde_json::Value)> = @@ -1812,6 +1955,12 @@ impl InstanceConfig { .filter(|(name, _)| { include_server_secrets || !SERVER_SECRET_SETTINGS.contains(&name.as_str()) }) + .map(|(name, mut value)| { + if !reveal_secrets { + redact_setting_secrets(&name, &mut value); + } + (name, value) + }) .collect(); let global_settings: GlobalSettings = serde_json::from_value(serde_json::Value::Object(map))?; @@ -2835,6 +2984,49 @@ mod tests { ); } + #[test] + fn redacted_settings_parse_and_restore_on_write() { + let stored = serde_json::json!({ + "custom_instance_pg_databases": { + "user_pwd": "pg-secret", + "databases": { "mydb": { "success": true, "tag": "t" } } + }, + "custom_instance_replication_pwd": "repl-secret", + "workspace_registries": { "ws": { "npm": { "token": "reg-secret" } } }, + "oauths": { "google": { "id": "client-id", "secret": "oauth-secret" } }, + "nuget_config": "<add key=\"ClearTextPassword\" value=\"nuget-secret\" />", + "otel": { "otel_exporter_otlp_endpoint": "https://otel", "otel_exporter_otlp_headers": "authorization=otel-secret" }, + "base_url": "https://example.com", + }); + let mut read = stored.clone(); + for (key, value) in read.as_object_mut().unwrap().iter_mut() { + redact_setting_secrets(key, value); + } + let text = read.to_string(); + for secret in [ + "pg-secret", + "repl-secret", + "reg-secret", + "oauth-secret", + "nuget-secret", + "otel-secret", + ] { + assert!(!text.contains(secret), "{secret} leaked: {text}"); + } + assert_eq!(read["oauths"]["google"]["id"], "client-id"); + assert_eq!(read["base_url"], "https://example.com"); + // The redacted read still parses into the typed config the API returns. + serde_json::from_value::<GlobalSettings>(read.clone()).unwrap(); + + for (key, value) in read.as_object_mut().unwrap().iter_mut() { + restore_redacted_secrets(key, value, stored.get(key)).unwrap(); + } + assert_eq!(read, stored); + + let mut orphan = serde_json::json!({ "smtp_password": REDACTED_SECRET }); + assert!(restore_redacted_secrets("smtp_settings", &mut orphan, None).is_err()); + } + #[test] fn db_oversize_alert_defaults() { let alert: DbOversizeAlert = serde_json::from_str("{}").unwrap(); @@ -2959,6 +3151,19 @@ mod tests { assert!(formatted.contains("****")); } + #[test] + fn format_setting_value_redacts_otel_headers() { + let val = serde_json::json!({ + "otel_exporter_otlp_endpoint": "http://collector:4317", + "otel_exporter_otlp_headers": "Authorization=Bearer main-token-12345", + "audit_logs_headers": "Authorization=Bearer audit-token-67890" + }); + let formatted = format_setting_value("otel", &val); + assert!(!formatted.contains("main-token-12345")); + assert!(!formatted.contains("audit-token-67890")); + assert!(formatted.contains("http://collector:4317")); + } + #[test] fn format_setting_value_redacts_nested_credentials() { let val = serde_json::json!({ @@ -3169,7 +3374,6 @@ mod tests { connect_config: None, login_config: None, tenant: None, - share_with_workspaces: None, grant_types: vec![], pkce: None, extra: BTreeMap::new(), diff --git a/backend/windmill-common/src/instance_ip_allowlist_oss.rs b/backend/windmill-common/src/instance_ip_allowlist_oss.rs new file mode 100644 index 0000000000..0eb6d42370 --- /dev/null +++ b/backend/windmill-common/src/instance_ip_allowlist_oss.rs @@ -0,0 +1,193 @@ +/* + * Author: Windmill Labs, Inc + * 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. + */ + +//! The instance IP allowlist (the `instance_ip_allowlist` setting) is an Enterprise Edition +//! feature. A community build never enforces a stored list and refuses to enable one, but still +//! lets one be turned off or cleared. + +use std::collections::HashMap; +use std::sync::LazyLock; + +use crate::global_settings::INSTANCE_IP_ALLOWLIST_SETTING; + +pub const ENV_DISABLED: &str = "INSTANCE_IP_ALLOWLIST_DISABLED"; + +/// The escape hatch: with it set the stored list is ignored, so an admin locked out can restart +/// the server with it, sign in and fix the list. +pub static DISABLED_BY_ENV: LazyLock<bool> = LazyLock::new(|| { + std::env::var(ENV_DISABLED) + .is_ok_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "true" | "1" | "yes")) +}); + +/// Reads the stored setting and puts it in force. +pub async fn reload(db: &crate::DB) { + match crate::global_settings::load_value_from_global_settings(db, INSTANCE_IP_ALLOWLIST_SETTING) + .await + { + Ok(v) => apply_setting(v.as_ref()), + Err(e) => tracing::error!("Error loading {INSTANCE_IP_ALLOWLIST_SETTING}: {e:#}"), + } +} + +/// Whether a write to `key` can change whether the stored allowlist may stay in force. +pub fn concerns(key: &str) -> bool { + key == INSTANCE_IP_ALLOWLIST_SETTING || crate::client_ip::SETTING_KEYS.contains(&key) +} + +/// Moves the allowlist and trust keys out of `diff`, for [`write_checked`] to write. +pub fn take_concerned( + diff: &mut crate::instance_config::SettingsDiff, +) -> HashMap<String, Option<serde_json::Value>> { + let mut taken = HashMap::new(); + diff.upserts.retain(|k, v| { + let c = concerns(k); + if c { + taken.insert(k.clone(), Some(v.clone())); + } + !c + }); + diff.deletes.retain(|k| { + let c = concerns(k); + if c { + taken.insert(k.clone(), None); + } + !c + }); + taken +} + +/// The only writer of the allowlist and the client IP trust. In one transaction holding a lock +/// every server takes for it, reads what is stored, checks what the write would leave in force +/// (the list, under the trust it would put in force, with `request` resolved under that trust; +/// `None` for the declarative sync, which has no request), and writes. Two writes checked apart, +/// such as the Client IP page saving the trust and the list as separate requests, would each be +/// checked against the other's old value and together store what neither check saw. One +/// connection only: the write holds no second one while it waits for the pool. +/// `written` maps each written key to its new value, `None` when it is cleared. +/// +/// AUTHORIZATION: checks nothing about the caller. Callers must have established that it may +/// change instance settings (a superadmin, or the declarative sync) before calling. +pub async fn write_checked( + db: &crate::DB, + written: &HashMap<String, Option<serde_json::Value>>, + request: Option<&crate::client_ip::RequestPeer>, +) -> crate::error::Result<()> { + if written.is_empty() { + return Ok(()); + } + let mut tx = db.begin().await?; + sqlx::query("SELECT pg_advisory_xact_lock(hashtext('instance_ip_allowlist_write'))") + .execute(&mut *tx) + .await?; + let mut values: HashMap<&str, Option<serde_json::Value>> = HashMap::new(); + for key in [INSTANCE_IP_ALLOWLIST_SETTING] + .into_iter() + .chain(crate::client_ip::SETTING_KEYS.iter().copied()) + { + let value = match written.get(key) { + Some(v) => v.clone(), + None => { + sqlx::query_scalar::<_, serde_json::Value>( + "SELECT value FROM global_settings WHERE name = $1", + ) + .bind(key) + .fetch_optional(&mut *tx) + .await? + } + }; + values.insert(key, value.filter(|v| !v.is_null())); + } + let get = |k: &str| values.get(k).and_then(|v| v.as_ref()); + let trust = crate::client_ip::settings_with( + get(crate::client_ip::TRUSTED_PROXIES_SETTING), + get(crate::client_ip::TRUST_CLOUDFLARE_SETTING), + get(crate::client_ip::CLIENT_IP_HEADER_SETTING), + ) + .await; + check_write( + get(INSTANCE_IP_ALLOWLIST_SETTING), + &trust, + request, + written.contains_key(INSTANCE_IP_ALLOWLIST_SETTING), + ) + .await + .map_err(|e| { + crate::error::Error::BadRequest(format!("{INSTANCE_IP_ALLOWLIST_SETTING}: {e}")) + })?; + for (key, value) in written { + match value { + Some(v) => { + sqlx::query( + "INSERT INTO global_settings (name, value) VALUES ($1, $2) \ + ON CONFLICT (name) DO UPDATE SET value = EXCLUDED.value, updated_at = now()", + ) + .bind(key) + .bind(v) + .execute(&mut *tx) + .await?; + } + None => { + sqlx::query("DELETE FROM global_settings WHERE name = $1") + .bind(key) + .execute(&mut *tx) + .await?; + } + } + tracing::info!("Wrote global setting {key}"); + } + tx.commit().await?; + Ok(()) +} + +#[cfg(all(feature = "private", feature = "enterprise"))] +pub use crate::instance_ip_allowlist_ee::{ + apply_setting, check_write, log_write, parse_setting, refused, +}; + +#[cfg(not(all(feature = "private", feature = "enterprise")))] +pub use ce::*; + +#[cfg(not(all(feature = "private", feature = "enterprise")))] +mod ce { + use std::net::IpAddr; + + use axum::http::{Extensions, HeaderMap}; + + use crate::client_ip::{ClientIpSettings, RequestPeer}; + + pub fn apply_setting(_value: Option<&serde_json::Value>) {} + + /// Validates nothing beyond what [`check_write`] refuses: the shape is the edition's. + pub fn parse_setting(_value: Option<&serde_json::Value>) -> Result<(), String> { + Ok(()) + } + + pub async fn check_write( + value: Option<&serde_json::Value>, + _trust: &ClientIpSettings, + _request: Option<&RequestPeer>, + _list_written: bool, + ) -> Result<(), String> { + match value.and_then(|v| v.get("enabled")) { + Some(serde_json::Value::Bool(true)) => Err( + "the instance IP allowlist is a Windmill Enterprise Edition feature".to_string(), + ), + _ => Ok(()), + } + } + + pub fn log_write(_value: Option<&serde_json::Value>) {} + + pub async fn refused( + _path: &str, + _extensions: &Extensions, + _headers: &HeaderMap, + ) -> Option<IpAddr> { + None + } +} diff --git a/backend/windmill-common/src/jobs.rs b/backend/windmill-common/src/jobs.rs index ecc2143c1c..1d6ace9ed5 100644 --- a/backend/windmill-common/src/jobs.rs +++ b/backend/windmill-common/src/jobs.rs @@ -240,55 +240,8 @@ pub async fn script_path_to_payload<'e>( ) } else { let script_info = - get_latest_deployed_hash_for_path(db_authed, db.clone(), w_id, script_path) - .await? - .prefetch_cached(&db) - .await?; - let on_behalf_of = script_info.on_behalf_of(w_id, &db).await?; - let ScriptHashInfo { - hash, - tag, - runnable_settings: - super::scripts::ScriptRunnableSettingsInline { - concurrency_settings, - debouncing_settings, - }, - cache_ttl, - cache_ignore_s3_path, - language, - dedicated_worker, - priority, - delete_after_use, - delete_after_secs, - timeout, - has_preprocessor, - labels, - job_token_scopes, - .. - } = script_info; - - ( - JobPayload::ScriptHash { - hash: ScriptHash(hash), - path: script_path.to_owned(), - cache_ttl, - cache_ignore_s3_path, - language, - dedicated_worker, - priority, - apply_preprocessor: !skip_preprocessor.unwrap_or(false) - && has_preprocessor.unwrap_or(false), - debouncing_settings, - concurrency_settings, - labels, - job_token_scopes, - }, - tag, - delete_after_use, - delete_after_secs, - timeout, - on_behalf_of, - ) + get_latest_deployed_hash_for_path(db_authed, db.clone(), w_id, script_path).await?; + script_info_to_payload(script_info, script_path, &db, w_id, skip_preprocessor).await? }; Ok(( job_payload, @@ -300,6 +253,69 @@ pub async fn script_path_to_payload<'e>( )) } +/// The payload, tag, retention, timeout and identity a run of one script version gets. +/// +/// Reads through `db` and authorizes nothing: callers must already have authorized the caller +/// for `w_id` and for the version `script_info` was read from, as the run routes do. +pub async fn script_info_to_payload( + script_info: ScriptHashInfo<super::scripts::ScriptRunnableSettingsHandle>, + script_path: &str, + db: &DB, + w_id: &str, + skip_preprocessor: Option<bool>, +) -> error::Result<( + JobPayload, + Option<Tag>, + Option<bool>, + Option<i32>, + Option<i32>, + Option<OnBehalfOf>, +)> { + let script_info = script_info.prefetch_cached(db).await?; + let on_behalf_of = script_info.on_behalf_of(w_id, db).await?; + let ScriptHashInfo { + hash, + tag, + runnable_settings: + super::scripts::ScriptRunnableSettingsInline { concurrency_settings, debouncing_settings }, + cache_ttl, + cache_ignore_s3_path, + language, + dedicated_worker, + priority, + delete_after_use, + delete_after_secs, + timeout, + has_preprocessor, + labels, + job_token_scopes, + .. + } = script_info; + + Ok(( + JobPayload::ScriptHash { + hash: ScriptHash(hash), + path: script_path.to_owned(), + cache_ttl, + cache_ignore_s3_path, + language, + dedicated_worker, + priority, + apply_preprocessor: !skip_preprocessor.unwrap_or(false) + && has_preprocessor.unwrap_or(false), + debouncing_settings, + concurrency_settings, + labels, + job_token_scopes, + }, + tag, + delete_after_use, + delete_after_secs, + timeout, + on_behalf_of, + )) +} + pub async fn runnable_ref_to_payload( runnable: &RunnableRef, origin: RunOrigin<'_>, diff --git a/backend/windmill-common/src/lib.rs b/backend/windmill-common/src/lib.rs index 822b0fda31..21179411bc 100644 --- a/backend/windmill-common/src/lib.rs +++ b/backend/windmill-common/src/lib.rs @@ -37,6 +37,7 @@ pub mod azure_workload_identity; pub mod bench; pub mod cache; pub mod client; +pub mod client_ip; pub mod data_metrics; pub mod datatable_roles; #[cfg(all(feature = "private", feature = "enterprise"))] @@ -81,6 +82,10 @@ pub mod guest_jwt; pub mod hub_resource_types; pub mod indexer; pub mod instance_config; +pub mod instance_ip_allowlist_oss; +pub use instance_ip_allowlist_oss as instance_ip_allowlist; +#[cfg(all(feature = "private", feature = "enterprise"))] +mod instance_ip_allowlist_ee; pub mod job_metrics; pub mod log_context; pub mod materialization; @@ -98,6 +103,7 @@ pub mod job_provenance; pub mod jobs; pub mod jwt; pub mod login_rate_limit; +pub mod request_origin; pub mod more_serde; pub mod oauth2; #[cfg(all(feature = "enterprise", feature = "openidconnect", feature = "private"))] @@ -482,6 +488,10 @@ lazy_static::lazy_static! { pub static ref OTEL_METRICS_ENABLED: AtomicBool = AtomicBool::new(std::env::var("OTEL_METRICS").is_ok()); pub static ref OTEL_TRACING_ENABLED: AtomicBool = AtomicBool::new(std::env::var("OTEL_TRACING").is_ok()); pub static ref OTEL_LOGS_ENABLED: AtomicBool = AtomicBool::new(std::env::var("OTEL_LOGS").is_ok()); + /// Leave audit events out of the logs export, for when the audit export carries them. + pub static ref OTEL_LOGS_EXCLUDE_AUDIT: AtomicBool = AtomicBool::new(env_bool("OTEL_LOGS_EXCLUDE_AUDIT")); + pub static ref OTEL_AUDIT_LOGS_EXPORT: std::sync::RwLock<Option<OtelAuditLogsExport>> = + std::sync::RwLock::new(OtelAuditLogsExport::from_env()); pub static ref METRICS_DEBUG_ENABLED: AtomicBool = AtomicBool::new(false); @@ -2162,6 +2172,162 @@ pub(crate) fn instance_db_grants(dbname: &str) -> String { ) } +/// An extension a managed database is created with, in `schema`. +#[derive(Clone, Debug, PartialEq)] +pub struct DatabaseExtension { + pub name: String, + pub schema: String, + /// The schema's comment, which the copy's own replay may not be allowed to set. + pub schema_comment: Option<String>, +} + +/// Create `extensions` in database `dbname`, just created, on `client`, the cluster +/// administrator's connection to it, before `custom_instance_user` holds anything there. +/// +/// An extension's script runs as the administrator and resolves names through the schemas it is +/// created in, so an object another role planted there first would run with the administrator's +/// rights. So `PUBLIC` loses `CREATE` on `public` (which Postgres before 15 grants), the database +/// must hold nothing that a role other than a superuser or the administrator owns, and a schema +/// made for an extension is the administrator's until the extension is in it, then +/// `custom_instance_user`'s, or failing that open to it, as in the database it was copied from. +pub(crate) async fn provision_extensions( + client: &tokio_postgres::Client, + dbname: &str, + extensions: &[DatabaseExtension], +) -> error::Result<()> { + if extensions.is_empty() { + return Ok(()); + } + let err = |context: &str, e: tokio_postgres::Error| { + error::Error::BadRequest(format!( + "{context} database '{dbname}': {}", + crate::error::pg_error_message(&e) + )) + }; + // Committed before the check, so nothing can be added to `public` behind it. + client + .batch_execute("REVOKE CREATE ON SCHEMA public FROM PUBLIC") + .await + .map_err(|e| err("Preparing", e))?; + let foreign: Vec<String> = client + .query( + "SELECT DISTINCT pg_get_userbyid(o.owner)::text FROM ( + SELECT relowner AS owner FROM pg_class UNION ALL + SELECT proowner FROM pg_proc UNION ALL + SELECT typowner FROM pg_type UNION ALL + SELECT oprowner FROM pg_operator UNION ALL + SELECT opcowner FROM pg_opclass UNION ALL + SELECT opfowner FROM pg_opfamily UNION ALL + SELECT collowner FROM pg_collation UNION ALL + SELECT conowner FROM pg_conversion UNION ALL + SELECT cfgowner FROM pg_ts_config UNION ALL + SELECT dictowner FROM pg_ts_dict UNION ALL + SELECT nspowner FROM pg_namespace UNION ALL + SELECT stxowner FROM pg_statistic_ext UNION ALL + SELECT extowner FROM pg_extension + ) o JOIN pg_roles r ON r.oid = o.owner + WHERE NOT r.rolsuper AND o.owner <> current_user::regrole + AND r.rolname <> 'pg_database_owner'", + &[], + ) + .await + .map_err(|e| err("Checking", e))? + .iter() + .map(|row| row.get(0)) + .collect(); + if !foreign.is_empty() { + return Err(error::Error::BadRequest(format!( + "Database '{dbname}' already holds objects of {}, so its extensions cannot be created \ + in it safely", + foreign.join(", ") + ))); + } + let mut setup = String::new(); + // Only a schema made here is handed over: one the database already has, `public` and + // `pg_catalog` among them, keeps its owner. + let existing: std::collections::BTreeSet<String> = client + .query("SELECT nspname::text FROM pg_namespace", &[]) + .await + .map_err(|e| err("Checking", e))? + .iter() + .map(|row| row.get(0)) + .collect(); + let schemas: std::collections::BTreeSet<&str> = extensions + .iter() + .map(|e| e.schema.as_str()) + .filter(|s| !existing.contains(*s)) + .collect(); + for schema in &schemas { + setup.push_str(&format!( + "CREATE SCHEMA IF NOT EXISTS {};\n", + datatable_roles::quote_ident(schema) + )); + } + for extension in extensions { + setup.push_str(&format!( + "CREATE EXTENSION IF NOT EXISTS {} WITH SCHEMA {} CASCADE;\n", + datatable_roles::quote_ident(&extension.name), + datatable_roles::quote_ident(&extension.schema) + )); + } + client + .batch_execute(&format!("BEGIN;\n{setup}COMMIT;")) + .await + .map_err(|e| err("Creating the extensions of", e))?; + // While the administrator still owns the schemas it made: the copy's role may own neither one + // the database already had nor one the handover below falls back from, and only an owner may + // comment on a schema. The server quotes the comment, the source's text, so no setting of + // `standard_conforming_strings` lets it end the literal. + for extension in extensions { + let Some(comment) = &extension.schema_comment else { + continue; + }; + let statement: Option<String> = client + .query_opt( + "SELECT format('COMMENT ON SCHEMA %I IS %L', $1::text, $2::text) + FROM pg_namespace + WHERE nspname = $1::text + AND obj_description(oid, 'pg_namespace') IS DISTINCT FROM $2::text", + &[&extension.schema, comment], + ) + .await + .map_err(|e| err("Checking", e))? + .map(|row| row.get(0)); + let Some(statement) = statement else { + continue; + }; + match client.batch_execute(&statement).await { + Ok(()) => {} + // A schema the database already had can be another superuser's: the copy goes without + // the comment rather than not at all. + Err(e) if !schemas.contains(extension.schema.as_str()) => tracing::warn!( + "Not copying the comment on schema '{}' to '{dbname}': {}", + extension.schema, + crate::error::pg_error_message(&e) + ), + Err(e) => return Err(err("Commenting the extension schemas of", e)), + } + } + for schema in schemas { + let schema = datatable_roles::quote_ident(schema); + let handed = client + .batch_execute(&format!( + "ALTER SCHEMA {schema} OWNER TO custom_instance_user" + )) + .await; + if handed.is_err() { + client + .batch_execute(&format!( + "GRANT USAGE, CREATE ON SCHEMA {schema} TO custom_instance_user \ + WITH GRANT OPTION" + )) + .await + .map_err(|e| err("Granting access to the extension schemas of", e))?; + } + } + Ok(()) +} + /// Re-apply [`instance_db_grants`] to a managed database provisioned before data table roles /// existed, whose grants carry no grant option. Connects as the cluster's administrator — the /// database and `public` schema owner — since only it can hand out an option it holds. @@ -2181,11 +2347,13 @@ pub async fn ensure_instance_db_grant_options_unchecked( /// Create a custom instance database: CREATE DATABASE, grant permissions, register in global_settings. /// The `tag` is stored in global_settings metadata (e.g. "datatable" or "ducklake"). `for_workspace` /// is the workspace a member creates a fork copy for; see [`ensure_fork_database_available_to`]. +/// `extensions` are created first, as [`provision_extensions`] does. pub async fn create_custom_instance_database( db: &DB, dbname: &str, tag: &str, for_workspace: Option<&str>, + extensions: &[DatabaseExtension], ) -> error::Result<()> { let dbname = dbname.trim(); validate_dbname(dbname)?; @@ -2215,7 +2383,9 @@ pub async fn create_custom_instance_database( // Nothing names a database that failed past this point, and its name blocks the retry: drop it // rather than leave it behind. - if let Err(e) = finish_custom_instance_database(db, dbname, tag, for_workspace).await { + if let Err(e) = + finish_custom_instance_database(db, dbname, tag, for_workspace, extensions).await + { match drop_unused_instance_database(db, dbname).await { Ok(Cleanup::InUse(users)) => tracing::warn!( "Kept '{dbname}' after failing to set it up: workspaces {} use it", @@ -2256,6 +2426,7 @@ async fn finish_custom_instance_database( dbname: &str, tag: &str, for_workspace: Option<&str>, + extensions: &[DatabaseExtension], ) -> error::Result<()> { // Grant permissions to custom_instance_user let wmill_pg_creds = PgDatabase::parse_uri(&get_database_url().await?.as_str().await)?; @@ -2263,6 +2434,13 @@ async fn finish_custom_instance_database( let (client, connection) = new_pg_creds.connect(Some(db)).await?; let join_handle = tokio::spawn(async move { connection.await }); + // Before the grants, as `provision_extensions` requires. + if let Err(e) = provision_extensions(&client, dbname, extensions).await { + drop(client); + let _ = shutdown_pg_connection(join_handle).await; + return Err(e); + } + if let Err(e) = client.batch_execute(&instance_db_grants(dbname)).await { tracing::warn!( "Failed to grant permissions on '{}': {}. Continuing.", @@ -2730,57 +2908,25 @@ pub fn get_latest_deployed_hash_for_path<'e>( async move { let cache_key = (w_id.to_string(), script_path.to_string()); let use_cache = !DEPLOYED_SCRIPT_CACHE_DISABLED.load(std::sync::atomic::Ordering::Relaxed); - let mut computed_hash = None; + // Resolved without the caller's RLS: the cache serves every caller, with an identity or + // none, so it must hold the path's deployed version, not the newest one a caller sees. let hash = match DEPLOYED_SCRIPT_HASH_CACHE .get(&cache_key) - .filter(|_| use_cache) + .filter(|cached| use_cache && cached.expires_at > std::time::Instant::now()) { - Some(cached_hash) - if cached_hash.expires_at > std::time::Instant::now() - && db.as_ref().is_none_or(|x| { - let r = HASH_PERMS_CACHE - .check_perms_in_cache(x.authed, ScriptHash(cached_hash.id)); - computed_hash = Some(r.1); - return r.0; - }) => - { + Some(cached_hash) => { tracing::debug!( "Using cached script hash {} for {script_path}", cached_hash.id ); cached_hash.id } - _ => { + None => { tracing::debug!("Fetching script hash for {script_path}"); - let latest = if let Some(db) = db { - let authed = db.authed; - let mut conn = db.acquire().await?; - let latest = - get_latest_deployed_script_hash(&mut *conn, script_path, w_id).await?; - if let Some(hash) = latest.hash { - HASH_PERMS_CACHE.insert( - computed_hash.unwrap_or_else(|| PermsCache::compute_hash(authed)), - ScriptHash(hash), - ); - } else { - // Release the user-db connection first: holding it while taking a - // second one from the same pool starves the pool under a burst of - // requests for paths the caller cannot see. - drop(conn); - let mut conn = db2.acquire().await?; - let exists = get_latest_script_hash(&mut *conn, script_path, w_id) - .await? - .is_some(); - if exists { - return Err(Error::NotAuthorized(format!("You are not authorized to access this script: {script_path} (but it exists). Your permissions are: {:?}", authed))); - } - } - latest - } else { + let latest = { let mut conn = db2.acquire().await?; get_latest_deployed_script_hash(&mut *conn, script_path, w_id).await? }; - let hash = utils::not_found_if_none(latest.hash, "script", script_path)?; if use_cache { let ttl = if latest.pending_lock { @@ -2796,11 +2942,31 @@ pub fn get_latest_deployed_hash_for_path<'e>( }, ); } - hash } }; + if let Some(db) = db { + let authed = db.authed; + let (cached, authed_hash) = + HASH_PERMS_CACHE.check_perms_in_cache(authed, ScriptHash(hash)); + if !cached { + let mut conn = db.acquire().await?; + let visible = sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM script WHERE hash = $1 AND workspace_id = $2)", + hash, + w_id + ) + .fetch_one(&mut *conn) + .await? + .unwrap_or(false); + if !visible { + return Err(Error::NotAuthorized(format!("You are not authorized to access this script: {script_path} (but it exists). Your permissions are: {:?}", authed))); + } + HASH_PERMS_CACHE.insert(authed_hash, ScriptHash(hash)); + } + } + get_script_info_for_hash(None, &db2, w_id, hash).await } } @@ -3467,3 +3633,58 @@ impl KillpillSender { // self.already_sent.load(Ordering::SeqCst) // } } + +fn env_bool(var: &str) -> bool { + std::env::var(var).is_ok_and(|x| x.parse::<bool>().unwrap_or(false)) +} + +/// An OTLP logs exporter of its own for audit events, beside the logs export: audit events can +/// go to long-term storage while the service logs go elsewhere, or nowhere. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OtelAuditLogsExport { + pub endpoint: String, + /// `key=value` pairs separated by commas, as in `OTEL_EXPORTER_OTLP_HEADERS`. + pub headers: Option<String>, + /// `grpc` (the default) or `http/protobuf`. + pub protocol: Option<String>, + /// Only the audit events of these workspaces, and of the instance itself, are exported. + /// `None` exports every workspace. + pub workspaces: Option<Vec<String>>, +} + +impl OtelAuditLogsExport { + pub fn new( + enabled: bool, + endpoint: Option<String>, + headers: Option<String>, + protocol: Option<String>, + workspaces: Option<Vec<String>>, + ) -> Option<Self> { + let endpoint = endpoint.filter(|e| !e.trim().is_empty())?; + enabled.then(|| Self { + endpoint: endpoint.trim().to_string(), + headers: headers.filter(|h| !h.trim().is_empty()), + protocol: protocol.filter(|p| !p.trim().is_empty()), + workspaces: workspaces + .map(|w| { + w.iter() + .map(|w| w.trim().to_string()) + .filter(|w| !w.is_empty()) + .collect::<Vec<_>>() + }) + .filter(|w| !w.is_empty()), + }) + } + + fn from_env() -> Option<Self> { + Self::new( + env_bool("OTEL_AUDIT_LOGS_ENABLED"), + std::env::var("OTEL_AUDIT_LOGS_ENDPOINT").ok(), + std::env::var("OTEL_AUDIT_LOGS_HEADERS").ok(), + std::env::var("OTEL_AUDIT_LOGS_PROTOCOL").ok(), + std::env::var("OTEL_AUDIT_LOGS_WORKSPACES") + .ok() + .map(|v| v.split(',').map(str::to_string).collect()), + ) + } +} diff --git a/backend/windmill-common/src/login_rate_limit.rs b/backend/windmill-common/src/login_rate_limit.rs index 8c60c30b88..d55f4dfe90 100644 --- a/backend/windmill-common/src/login_rate_limit.rs +++ b/backend/windmill-common/src/login_rate_limit.rs @@ -53,32 +53,6 @@ static GLOBAL_LIMIT: LazyLock<i32> = LazyLock::new(|| { .unwrap_or(DEFAULT_GLOBAL_LIMIT) }); -/// Extract client IP from proxy headers. Only meaningful when behind a trusted -/// reverse proxy (e.g. CLOUD_HOSTED). Returns `None` if no proxy header is present. -pub fn extract_client_ip(headers: &axum::http::HeaderMap) -> Option<String> { - if let Some(real_ip) = headers.get("x-real-ip") { - if let Ok(ip) = real_ip.to_str() { - let trimmed = ip.trim(); - if !trimmed.is_empty() { - return Some(trimmed.to_string()); - } - } - } - - if let Some(forwarded_for) = headers.get("x-forwarded-for") { - if let Ok(ips) = forwarded_for.to_str() { - if let Some(first_ip) = ips.split(',').next() { - let trimmed = first_ip.trim(); - if !trimmed.is_empty() { - return Some(trimmed.to_string()); - } - } - } - } - - None -} - fn too_many_attempts() -> Error { Error::Generic( StatusCode::TOO_MANY_REQUESTS, @@ -91,7 +65,7 @@ fn too_many_attempts() -> Error { /// a general throttle on login traffic per server instance. /// Per-IP is only active on CLOUD_HOSTED or when LOGIN_RATE_LIMIT_PER_IP is explicitly set. pub fn check_and_increment_login_attempt( - headers: &axum::http::HeaderMap, + client_ip: Option<std::net::IpAddr>, email: &str, ) -> Result<()> { // Global limit: always on, uses atomics (single key, no need for a map) @@ -99,8 +73,8 @@ pub fn check_and_increment_login_attempt( // Per-IP limit: CLOUD_HOSTED or explicit opt-in if *CLOUD_HOSTED || *PER_IP_LIMIT_EXPLICIT { - if let Some(ip) = extract_client_ip(headers) { - if !IP_RATE_LIMIT.try_increment(ip, *PER_IP_LIMIT) { + if let Some(ip) = client_ip { + if !IP_RATE_LIMIT.try_increment(ip.to_string(), *PER_IP_LIMIT) { return Err(too_many_attempts()); } } diff --git a/backend/windmill-common/src/min_version.rs b/backend/windmill-common/src/min_version.rs index 25a97c2806..f5ec9b00db 100644 --- a/backend/windmill-common/src/min_version.rs +++ b/backend/windmill-common/src/min_version.rs @@ -48,7 +48,7 @@ pub const MIN_VERSION_SUPPORTS_LEASE_FREE_VOLUMES: VC = vc(1, 872, 0, "Lease-fre // worker that predates it rejects that status and fails the restart. Must name the release // this ships in. pub const MIN_VERSION_SUPPORTS_FAILED_ONLY_RESTART: VC = - vc(1, 883, 0, "Rerun only failed iterations"); + vc(1, 884, 0, "Rerun only failed iterations"); // A worker that predates `FlowStatus::test_subflows` ignores it and runs the deployed subflow, // so a step the test mocks would run for real. Must name the release this ships in. pub const MIN_VERSION_SUPPORTS_FLOW_TEST_SUBFLOWS: VC = diff --git a/backend/windmill-common/src/otel_oss.rs b/backend/windmill-common/src/otel_oss.rs index 9dac8a07db..4de717278b 100644 --- a/backend/windmill-common/src/otel_oss.rs +++ b/backend/windmill-common/src/otel_oss.rs @@ -63,6 +63,20 @@ pub(crate) fn init_logs_bridge_for_service( None } +#[cfg(not(feature = "private"))] +pub(crate) fn init_audit_logs_bridge(_mode: &Mode, _hostname: &str, _env: &str) -> Option<EnvFilter> { + None +} + +#[cfg(not(feature = "private"))] +pub(crate) fn init_audit_logs_bridge_for_service( + _service: &str, + _hostname: &str, + _env: &str, +) -> Option<EnvFilter> { + None +} + /// Export the log records still batched, for a process about to exit. #[cfg(not(feature = "private"))] pub async fn flush_otel_logs() {} diff --git a/backend/windmill-common/src/query_builders.rs b/backend/windmill-common/src/query_builders.rs index 145228abdf..59d1a7379e 100644 --- a/backend/windmill-common/src/query_builders.rs +++ b/backend/windmill-common/src/query_builders.rs @@ -442,7 +442,37 @@ pub fn try_expand_internal_db_query( _ => Err(format!("Unknown WM_INTERNAL_DB operation: {}", op)), }; - Some(result) + // The SQL executors replace `%%WM_*%%` contextual variables anywhere in the script, quoted + // or not, so a table, column or type name spelling one would receive the viewer's value. + Some(result.and_then(|expanded| { + if expanded.code.contains("%%WM_") { + Err("Names containing `%%WM_` are not supported by the database manager".to_string()) + } else { + Ok(expanded) + } + })) +} + +/// Column names and types are written into `-- $1 name (type)` parameter declarations, which +/// a line break would end, turning the rest of the name into script lines. +fn check_param_columns<'a>( + columns: impl IntoIterator<Item = (&'a str, &'a str)>, +) -> Result<(), String> { + for (field, datatype) in columns { + if field.chars().chain(datatype.chars()).any(char::is_control) { + return Err(format!( + "Column {field:?} of type {datatype:?}: names and types containing control \ + characters are not supported by the database manager" + )); + } + } + Ok(()) +} + +fn column_def_pairs(columns: &[ColumnDef]) -> impl Iterator<Item = (&str, &str)> { + columns + .iter() + .map(|c| (c.field.as_str(), c.datatype.as_str())) } impl ExpandedQuery { @@ -542,6 +572,7 @@ fn pk_columns_or_all(columns: &[ColumnDef]) -> Vec<ColumnDef> { fn expand_delete(json_str: &str, db_type: DbType) -> Result<String, String> { let payload: DeletePayload = serde_json::from_str(json_str).map_err(|e| format!("Invalid DELETE payload: {}", e))?; + check_param_columns(column_def_pairs(&payload.columns))?; let where_columns = pk_columns_or_all(&payload.columns); let query = make_delete_query(&payload.table, &where_columns, db_type); @@ -551,6 +582,7 @@ fn expand_delete(json_str: &str, db_type: DbType) -> Result<String, String> { fn expand_insert(json_str: &str, db_type: DbType) -> Result<String, String> { let payload: InsertPayload = serde_json::from_str(json_str).map_err(|e| format!("Invalid INSERT payload: {}", e))?; + check_param_columns(column_def_pairs(&payload.columns))?; let query = make_insert_query(&payload.table, &payload.columns, db_type)?; Ok(maybe_wrap_ducklake(query, payload.ducklake.as_deref())) @@ -559,6 +591,10 @@ fn expand_insert(json_str: &str, db_type: DbType) -> Result<String, String> { fn expand_update(json_str: &str, db_type: DbType) -> Result<String, String> { let payload: UpdatePayload = serde_json::from_str(json_str).map_err(|e| format!("Invalid UPDATE payload: {}", e))?; + check_param_columns(column_def_pairs(&payload.columns).chain([( + payload.column.field.as_str(), + payload.column.datatype.as_str(), + )]))?; let where_columns = pk_columns_or_all(&payload.columns); let where_simple = cols_to_simple(&where_columns); @@ -3167,11 +3203,18 @@ mod tests { &[simple_col("js", "jsonb")], DbType::Postgresql, ); - assert!(update.contains(r#"SET "js" = $1::text::jsonb"#), "{}", update); + assert!( + update.contains(r#"SET "js" = $1::text::jsonb"#), + "{}", + update + ); assert!(update.contains(r#""js"::text = $2::text"#), "{}", update); - let insert = - make_insert_query("t", &[col("id", "int4"), col("js", "jsonb")], DbType::Postgresql) - .unwrap(); + let insert = make_insert_query( + "t", + &[col("id", "int4"), col("js", "jsonb")], + DbType::Postgresql, + ) + .unwrap(); assert!(insert.contains("VALUES ($1, $2::text::jsonb"), "{}", insert); let delete = make_delete_query("t", &[col("js", "json")], DbType::Postgresql); assert!(delete.contains(r#""js"::text = $1::text"#), "{}", delete); @@ -4193,6 +4236,31 @@ mod tests { assert!(result.unwrap().is_err()); } + #[test] + fn test_expand_refuses_line_breaks_in_parameter_names() { + for marker in [ + r#"-- WM_INTERNAL_DB_DELETE {"table":"t","columns":[{"field":"id","datatype":"x\n-- database u/a/b"}]}"#, + r#"-- WM_INTERNAL_DB_INSERT {"table":"t","columns":[{"field":"a\rSELECT 1;","datatype":"text"}]}"#, + r#"-- WM_INTERNAL_DB_UPDATE {"table":"t","column":{"field":"a\nb","datatype":"text"},"columns":[{"field":"id","datatype":"int4"}]}"#, + ] { + let result = try_expand_internal_db_query(marker, &ScriptLang::Postgresql); + assert!(result.unwrap().is_err(), "{marker}"); + } + } + + #[test] + fn test_expand_refuses_contextual_variable_names() { + let marker = r#"-- WM_INTERNAL_DB_SELECT {"table":"t","columnDefs":[{"field":"%%WM_TOKEN%%","datatype":"text"}]}"#; + for lang in [ + ScriptLang::Postgresql, + ScriptLang::Mysql, + ScriptLang::DuckDb, + ] { + let result = try_expand_internal_db_query(marker, &lang); + assert!(result.unwrap().is_err()); + } + } + #[test] fn test_expand_mysql_select() { let marker = r#"-- WM_INTERNAL_DB_SELECT {"table":"users","columnDefs":[{"field":"id","datatype":"int"},{"field":"name","datatype":"varchar"}]}"#; diff --git a/backend/windmill-common/src/request_origin.rs b/backend/windmill-common/src/request_origin.rs new file mode 100644 index 0000000000..e5db1da405 --- /dev/null +++ b/backend/windmill-common/src/request_origin.rs @@ -0,0 +1,64 @@ +//! Where the request being served came from, as recorded on the audit entries it writes: the +//! client's address in the attributed view (`client_ip.rs`), its user agent, and, because a +//! private peer can name any address in that view, the connection's own peer and the forwarding +//! header as received. + +use std::net::IpAddr; +use std::sync::Arc; + +use http::HeaderMap; + +use crate::utils::truncate_chars; + +const USER_AGENT_MAX_CHARS: usize = 512; +const FORWARDED_FOR_MAX_CHARS: usize = 512; + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RequestOrigin { + pub client_ip: Option<IpAddr>, + pub user_agent: Option<String>, + /// The connection's peer, when it is not `client_ip`. + pub peer_ip: Option<IpAddr>, + /// The forwarding header as received, believed or not. + pub forwarded_for: Option<String>, +} + +tokio::task_local! { + static REQUEST_ORIGIN: Arc<RequestOrigin>; +} + +/// Run `f` with `origin` as the origin of every audit entry it writes. Task-locals do not +/// cross `tokio::spawn`, so an entry written from a spawned task records no origin. +pub async fn scope<F: std::future::Future>(origin: RequestOrigin, f: F) -> F::Output { + REQUEST_ORIGIN.scope(Arc::new(origin), f).await +} + +/// The origin of the request being served, `None` outside a request. +pub fn current() -> Option<Arc<RequestOrigin>> { + REQUEST_ORIGIN.try_with(|o| o.clone()).ok() +} + +impl RequestOrigin { + /// `peer` is the address the connection came from; `None` when the request did not arrive + /// over a socket, and then no header is believed either. + pub fn from_request(peer: Option<IpAddr>, headers: &HeaderMap) -> Self { + let peer = peer.map(crate::client_ip::canonical); + let client_ip = peer.map(|p| crate::client_ip::attributed_client_ip(p, headers)); + if let Some(p) = peer { + crate::client_ip::note_forwarder(p, headers); + } + Self { + client_ip, + peer_ip: peer.filter(|p| Some(*p) != client_ip), + forwarded_for: peer.and(crate::client_ip::forwarding_header(headers)).map(|f| { + truncate_chars(&f, FORWARDED_FOR_MAX_CHARS).to_string() + }), + user_agent: headers + .get(http::header::USER_AGENT) + .and_then(|v| v.to_str().ok()) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(|s| truncate_chars(s, USER_AGENT_MAX_CHARS).to_string()), + } + } +} diff --git a/backend/windmill-common/src/scopes.rs b/backend/windmill-common/src/scopes.rs index 8549e673ba..bf834a9968 100644 --- a/backend/windmill-common/src/scopes.rs +++ b/backend/windmill-common/src/scopes.rs @@ -93,6 +93,24 @@ impl ScopeDefinition { } } + /// Parses the scope an operation on one item needs. Its path is taken whole: a `,` or + /// `*` in a request path is part of the name, not a list or a pattern, so it must not be + /// read with the grant grammar of [`Self::from_scope_string`]. + pub fn from_required_scope_string(scope: &str) -> Result<Self> { + let mut def = Self::from_scope_string(scope)?; + if def.resource.is_some() { + let path = scope.rsplit(':').next().unwrap_or_default(); + def.resource = Some(vec![path.to_string()]); + } + Ok(def) + } + + /// Whether this grant covers `required`, a scope parsed with + /// [`Self::from_required_scope_string`]. Only the grant side is read as a pattern. + pub fn grants(&self, required: &ScopeDefinition) -> bool { + scope_contains(self, required) + } + pub fn as_string(&self) -> String { match (&self.kind, &self.resource) { (Some(kind), Some(resource)) => { @@ -514,6 +532,15 @@ pub fn scope_contains(caller: &ScopeDefinition, requested: &ScopeDefinition) -> } match (&caller.resource, &requested.resource) { + // A `resources:` pattern also resolves the variables it matches + // (`check_resource_var_ref_scope`), which a pathless `resources:` scope does not, + // so the pattern is not narrower than it. + (None, Some(requested_resources)) + if caller.domain == "resources" + && requested_resources.iter().any(|r| r.contains('*')) => + { + false + } // Caller is unrestricted on resources: covers everything. (None, _) => true, // Caller is resource-restricted but the request is not: broader, unless the @@ -726,6 +753,26 @@ mod job_token_scopes_tests { ); } + #[test] + fn pathless_resources_scope_does_not_contain_patterns() { + let s = |x: &str| ScopeDefinition::from_scope_string(x).unwrap(); + let contains = |caller: &str, requested: &str| scope_contains(&s(caller), &s(requested)); + for requested in ["resources:read:*", "resources:read:f/a/*"] { + assert!(!contains("resources:read", requested)); + assert!(!contains("resources:write", requested)); + } + assert!(contains("resources:read", "resources:read:f/a/b")); + assert!(contains("resources:write:*", "resources:read:f/a/*")); + assert!(contains("variables:read", "variables:read:f/a/*")); + assert_eq!( + intersect_job_token_scopes( + Some(&v(&["resources:read"])), + Some(&v(&["resources:read:*"])) + ), + Some(v(&["resources:read"])) + ); + } + #[test] fn empty_effective_scopes_mint_a_scoped_token() { assert_eq!( diff --git a/backend/windmill-common/src/tracing_init.rs b/backend/windmill-common/src/tracing_init.rs index 855e077004..baf1d831e4 100644 --- a/backend/windmill-common/src/tracing_init.rs +++ b/backend/windmill-common/src/tracing_init.rs @@ -67,6 +67,14 @@ fn create_targets_filter(default_env_filter: LevelFilter) -> Targets { } } +fn audit_filter() -> Targets { + Targets::new().with_target(AUDIT_TARGET, LevelFilter::INFO) +} + +fn not_audit_filter() -> tracing_subscriber::filter::FilterFn<impl Fn(&tracing::Metadata<'_>) -> bool> { + tracing_subscriber::filter::filter_fn(|m| m.target() != AUDIT_TARGET) +} + pub const LOGS_SERVICE: &str = "logs/services/"; pub const LOGS_AUDIT: &str = "logs/audit/"; @@ -120,6 +128,7 @@ pub fn initialize_tracing( let opentelemetry: Option<EnvFilter> = None; let logs_bridge = crate::otel_oss::init_logs_bridge(&mode, hostname, environment); + let audit_logs_bridge = crate::otel_oss::init_audit_logs_bridge(&mode, hostname, environment); use tracing_appender::rolling::{RollingFileAppender, Rotation}; @@ -168,6 +177,9 @@ pub fn initialize_tracing( // Create a common filter for OTEL logs bridge and tracing layer to respect RUST_LOG let otel_logs_filter = file_env_filter.clone(); + let otel_logs_without_audit = crate::OTEL_LOGS_EXCLUDE_AUDIT + .load(std::sync::atomic::Ordering::Relaxed) + .then(not_audit_filter); // Apply filter to the opentelemetry tracing layer to prevent debug events from being attached to spans #[cfg(all(feature = "otel", feature = "enterprise"))] @@ -180,7 +192,17 @@ pub fn initialize_tracing( let opentelemetry_filtered = opentelemetry; let base_layer = tracing_subscriber::registry() - .with(logs_bridge.with_filter(otel_logs_filter)) + .with( + logs_bridge + .with_filter(otel_logs_filter) + .with_filter(otel_logs_without_audit), + ) + // Audit events reach their own export whatever RUST_LOG is set to. + .with( + audit_logs_bridge + .with_filter(audit_filter()) + .with_filter(audit_workspace_filter()), + ) .with(opentelemetry_filtered); // The service log files are written to be indexed, not tailed, so they always carry the @@ -229,9 +251,18 @@ pub fn initialize_tracing( /// value, masked by a list of known secret fields rather than by shape, and that is fit /// for the operator's own stdout but not for a collector. pub fn initialize_subcommand_tracing(service: &str, hostname: &str, environment: &str) { - let logs_bridge = crate::otel_oss::init_logs_bridge_for_service(service, hostname, environment); + let logs_bridge = (!crate::OTEL_LOGS_EXCLUDE_AUDIT.load(std::sync::atomic::Ordering::Relaxed)) + .then(|| crate::otel_oss::init_logs_bridge_for_service(service, hostname, environment)) + .flatten(); + let audit_logs_bridge = + crate::otel_oss::init_audit_logs_bridge_for_service(service, hostname, environment); tracing_subscriber::registry() - .with(logs_bridge.with_filter(Targets::new().with_target(AUDIT_TARGET, LevelFilter::INFO))) + .with(logs_bridge.with_filter(audit_filter())) + .with( + audit_logs_bridge + .with_filter(audit_filter()) + .with_filter(audit_workspace_filter()), + ) .with( tracing_subscriber::fmt::layer().with_filter( EnvFilter::builder() @@ -242,6 +273,50 @@ pub fn initialize_subcommand_tracing(service: &str, hostname: &str, environment: .init(); } +/// Keeps the audit events of the listed workspaces and lets every other event through. +/// Entries about the instance itself are recorded under workspace `global` and always kept: +/// no workspace stands behind them, and dropping them would hide settings changes. +struct AuditWorkspaceFilter(std::collections::HashSet<String>); + +impl AuditWorkspaceFilter { + fn new(workspaces: Vec<String>) -> Self { + Self(workspaces.into_iter().collect()) + } +} + +impl<S> tracing_subscriber::layer::Filter<S> for AuditWorkspaceFilter { + fn enabled(&self, _: &tracing::Metadata<'_>, _: &Context<'_, S>) -> bool { + true + } + + fn event_enabled(&self, event: &Event<'_>, _: &Context<'_, S>) -> bool { + if event.metadata().target() != AUDIT_TARGET { + return true; + } + struct Workspace<'a>(&'a std::collections::HashSet<String>, Option<bool>); + impl tracing::field::Visit for Workspace<'_> { + fn record_str(&mut self, field: &tracing::field::Field, value: &str) { + if field.name() == "workspace_id" { + self.1 = Some(value == "global" || self.0.contains(value)); + } + } + fn record_debug(&mut self, _: &tracing::field::Field, _: &dyn std::fmt::Debug) {} + } + let mut ws = Workspace(&self.0, None); + event.record(&mut ws); + ws.1.unwrap_or(true) + } +} + +/// The workspace scope of the audit export, `None` for every workspace. +fn audit_workspace_filter() -> Option<AuditWorkspaceFilter> { + crate::OTEL_AUDIT_LOGS_EXPORT + .read() + .ok() + .and_then(|e| e.as_ref().and_then(|e| e.workspaces.clone())) + .map(AuditWorkspaceFilter::new) +} + lazy_static::lazy_static! { pub static ref LOG_COUNTING_BY_MIN: Arc<RwLock<HashMap<String, LogCounter>>> = Arc::new(RwLock::new(HashMap::new())); } @@ -290,3 +365,54 @@ where } } } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Mutex; + + #[derive(Clone, Default)] + struct Seen(Arc<Mutex<Vec<String>>>); + + impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for Seen { + fn on_event(&self, event: &Event<'_>, _: Context<'_, S>) { + struct Msg(String); + impl tracing::field::Visit for Msg { + fn record_debug(&mut self, f: &tracing::field::Field, v: &dyn std::fmt::Debug) { + if f.name() == "message" { + self.0 = format!("{v:?}"); + } + } + } + let mut m = Msg(String::new()); + event.record(&mut m); + self.0.lock().unwrap().push(m.0); + } + } + + /// The two exports as `initialize_tracing` filters them: the logs export without audit + /// events, and the audit export with audit events of the listed workspaces only. + #[test] + fn audit_and_logs_exports_split_events() { + let logs = Seen::default(); + let audit = Seen::default(); + tracing::subscriber::with_default( + tracing_subscriber::registry() + .with(logs.clone().with_filter(Some(not_audit_filter()))) + .with( + audit + .clone() + .with_filter(audit_filter()) + .with_filter(Some(AuditWorkspaceFilter::new(vec!["kept".to_string()]))), + ), + || { + tracing::info!(target: AUDIT_TARGET, workspace_id = "kept", "a"); + tracing::info!(target: AUDIT_TARGET, workspace_id = "dropped", "b"); + tracing::info!(target: AUDIT_TARGET, workspace_id = "global", "c"); + tracing::info!(workspace_id = "kept", "d"); + }, + ); + assert_eq!(*logs.0.lock().unwrap(), ["d"]); + assert_eq!(*audit.0.lock().unwrap(), ["a", "c"]); + } +} diff --git a/backend/windmill-common/src/utils.rs b/backend/windmill-common/src/utils.rs index 541df5b17e..343d4d0d05 100644 --- a/backend/windmill-common/src/utils.rs +++ b/backend/windmill-common/src/utils.rs @@ -367,10 +367,21 @@ pub async fn require_admin_or_devops( // branch on a workspace it isn't admin of (GHSA-hfh4-cx4h-3fcr). Workspace admin // (`is_admin`) stays allowed — that is the cap ceiling. is_job_token: bool, + // True when the caller's token withholds its owner's superadmin rights: only the + // account's own devops role counts then, not the one a superadmin implies. + super_admin_withheld: bool, db: &DB, ) -> Result<()> { if !is_admin { - if is_job_token || !is_devops_email(db, email).await? { + let is_devops = if super_admin_withheld { + sqlx::query_scalar!("SELECT devops FROM password WHERE email = $1", email) + .fetch_optional(db) + .await? + .unwrap_or(false) + } else { + is_devops_email(db, email).await? + }; + if is_job_token || !is_devops { return Err(Error::RequireAdmin(username.to_string())); } } diff --git a/backend/windmill-common/src/variables.rs b/backend/windmill-common/src/variables.rs index 6656f334de..b56e9938c1 100644 --- a/backend/windmill-common/src/variables.rs +++ b/backend/windmill-common/src/variables.rs @@ -63,7 +63,8 @@ pub fn omit_untrusted_interpolation( to_raw_value(&d) } None => to_raw_value( - &"This argument has been omitted for security reasons: it could not be checked", + &"This argument was not passed: it could not be checked for variable or \ + resource references", ), }; (k, v) @@ -74,12 +75,12 @@ pub fn omit_untrusted_interpolation( /// `text`, handed as a string to jobs that run under another identity than its writer's, with /// every reference rewritten as [`omit_untrusted_interpolation`] would. pub fn omit_untrusted_text(text: &str) -> String { - omitted( - text, - "The following resource has been omitted for security reasons: ", - ) + omitted(text, UNRESOLVED_RESOURCE) } +/// What replaces a `$res:` prefix the worker is not to resolve, before the path it named. +pub const UNRESOLVED_RESOURCE: &str = "The following resource reference was not resolved: "; + /// Without a `$`, spelled out or escaped, an argument holds no reference however jsonb rewrites /// it, so it needs no decoding, even one serde_json cannot read. fn may_reference(arg: &str) -> bool { @@ -137,14 +138,14 @@ fn reserved(s: &str) -> Option<&str> { } fn omitted(s: &str, resource_omitted: &str) -> String { - let variable = "The following variable has been omitted for security reasons: "; + let variable = "The following variable reference was not resolved: "; if let Some(n) = reserved(s) { return format!("{variable}{n}"); } RE_RES_VAR .replace_all(s, |c: ®ex::Captures| match &c[1] { "res" => resource_omitted, - "encrypted" => "The following encrypted value has been omitted for security reasons: ", + "encrypted" => "The following encrypted value was not resolved: ", _ => variable, }) .into_owned() @@ -1124,7 +1125,7 @@ mod tests { let arg = serde_json::value::RawValue::from_string(s.to_string()).unwrap(); omit_untrusted_interpolation( [("a".to_string(), arg)].into(), - "The following resource has been omitted for security reasons: ", + super::UNRESOLVED_RESOURCE, )["a"] .get() .to_string() @@ -1151,7 +1152,7 @@ mod tests { !arg_needs_interpolation(&out) && !out.contains("$WM_"), "{hit}: {out}" ); - assert!(out.contains("omitted for security reasons"), "{hit}: {out}"); + assert!(out.contains("was not resolved"), "{hit}: {out}"); } assert!(omit(r#"{"n": 1e400, "r": "$var:x"}"#).contains("could not be checked")); assert_eq!(omit(r#"{"n": 1e400}"#), r#"{"n": 1e400}"#); diff --git a/backend/windmill-common/src/workspaces.rs b/backend/windmill-common/src/workspaces.rs index 907d8b5767..3ef4dce5fb 100644 --- a/backend/windmill-common/src/workspaces.rs +++ b/backend/windmill-common/src/workspaces.rs @@ -81,6 +81,7 @@ bitflags::bitflags! { const RESTRICT_PUBLIC_RUN_SHARING = 1 << 4; const RESTRICT_GUEST_APP_DEPLOYMENT = 1 << 5; const REQUIRE_ISOLATED_FORKS = 1 << 6; + const REQUIRE_SSO = 1 << 7; } } @@ -95,6 +96,7 @@ pub enum ProtectionRuleKind { RestrictPublicRunSharing, RestrictGuestAppDeployment, RequireIsolatedForks, + RequireSso, } impl ProtectionRuleKind { @@ -119,6 +121,7 @@ impl ProtectionRuleKind { ProtectionRules::RESTRICT_GUEST_APP_DEPLOYMENT } ProtectionRuleKind::RequireIsolatedForks => ProtectionRules::REQUIRE_ISOLATED_FORKS, + ProtectionRuleKind::RequireSso => ProtectionRules::REQUIRE_SSO, } } @@ -143,6 +146,9 @@ impl ProtectionRuleKind { ProtectionRuleKind::RequireIsolatedForks => { "Forks of this workspace must isolate its data: no shared object storage or ducklake, and every data table cloned" } + ProtectionRuleKind::RequireSso => { + "Every member of this workspace other than a service account must sign in with SSO" + } } } } @@ -844,6 +850,10 @@ pub async fn fork_subtree_height(db: &crate::DB, w_id: &str) -> Result<i64> { /// a narrow membership right over the fork; the callers own the exact bounds of that grant (see /// `add_user` in `windmill-api-workspaces`). /// +/// The grant holds only while the creator is still an enabled developer (or admin) of the fork, +/// read from the database rather than the session: a creator whom an admin of the fork restricted, +/// or who left it, must not be able to seat developers, themselves included. +/// /// Unauthenticated helper: reads workspace hierarchy for any `w_id`, so callers must already be /// authorized for that workspace (or run in trusted server-side code). Takes any executor so that a /// caller can run it inside the transaction whose writes the grant authorizes. @@ -852,16 +862,22 @@ pub async fn fork_owned_by<'e, E: sqlx::Executor<'e, Database = sqlx::Postgres>> w_id: &str, email: &str, ) -> Result<Option<String>> { - let parent = sqlx::query_scalar!( - "SELECT parent_workspace_id FROM workspace - WHERE id = $1 AND owner = $2 AND parent_workspace_id IS NOT NULL AND NOT deleted", - w_id, - email + let row = sqlx::query_as::<_, (Option<String>, bool, Option<String>, bool)>( + "SELECT w.parent_workspace_id, u.is_admin, u.workspace_role, u.operator + FROM workspace w + JOIN usr u ON u.workspace_id = w.id AND u.email = w.owner AND NOT u.disabled + WHERE w.id = $1 AND w.owner = $2 AND w.parent_workspace_id IS NOT NULL AND NOT w.deleted", ) + .bind(w_id) + .bind(email) .fetch_optional(db) .await .map_err(|e| Error::internal_err(format!("checking fork ownership of {w_id}: {e:#}")))?; - Ok(parent.flatten()) + let Some((parent, is_admin, workspace_role, operator)) = row else { + return Ok(None); + }; + let role = crate::roles::resolve_role_name(workspace_role, operator); + Ok(parent.filter(|_| is_admin || role == crate::roles::DEVELOPER_ROLE)) } /// Ids of every fork/dev workspace anywhere under `w_id` (excludes `w_id` itself), including live @@ -1555,6 +1571,117 @@ pub async fn check_user_against_rule( Ok(RuleCheckResult::Allowed) } +struct SsoRuleset { + name: String, + bypass_users: Vec<String>, + bypass_groups: Vec<String>, +} + +/// `workspace_id`'s `RequireSso` rulesets, read uncached so a rule just turned on already +/// refuses the next join. +async fn sso_rulesets( + conn: &mut sqlx::PgConnection, + workspace_id: &str, +) -> Result<Vec<SsoRuleset>> { + Ok(sqlx::query_as!( + SsoRuleset, + "SELECT name, bypass_users, bypass_groups FROM workspace_protection_rule + WHERE workspace_id = $1 AND (rules & $2) <> 0 ORDER BY name", + workspace_id, + ProtectionRules::REQUIRE_SSO.bits(), + ) + .fetch_all(&mut *conn) + .await?) +} + +/// The first of `rulesets` that holds a member named `username` in `groups`. +fn sso_ruleset_holding<'a>( + rulesets: &'a [SsoRuleset], + username: Option<&str>, + groups: &[String], +) -> Option<&'a str> { + rulesets + .iter() + .find(|r| { + !(username.is_some_and(|u| r.bypass_users.iter().any(|b| b == u)) + || r.bypass_groups.iter().any(|g| groups.contains(g))) + }) + .map(|r| r.name.as_str()) +} + +/// Refuses seating `email` in `workspace_id` while a `RequireSso` rule there holds them and their +/// account signs in with a password. `pending_oauth` passes: it can only become a password +/// account through [`check_password_login_allowed`]. An email with no account yet passes too, for +/// the same reason. `username` is the one they get in the workspace; without it their instance +/// username is what bypass lists are matched against. A new member is in `all` and nothing else. +/// +/// This and [`check_password_login_allowed`] each read what the other writes without locking, so +/// a join and a password switch of the same account committing at the same instant can both pass. +/// A lock shared by both would have to be taken in one order with the invite, membership and +/// `password` row locks of every member path, bulk joins included, or it deadlocks them. +pub async fn check_new_member_sso( + conn: &mut sqlx::PgConnection, + workspace_id: &str, + email: &str, + username: Option<&str>, +) -> Result<()> { + let rulesets = sso_rulesets(conn, workspace_id).await?; + if rulesets.is_empty() { + return Ok(()); + } + let account = sqlx::query!( + "SELECT login_type, username FROM password WHERE email = $1", + email + ) + .fetch_optional(&mut *conn) + .await?; + let Some(account) = account.filter(|a| a.login_type == "password") else { + return Ok(()); + }; + let username = username.or(account.username.as_deref()); + let groups = ["all".to_string()]; + if let Some(ruleset) = sso_ruleset_holding(&rulesets, username, &groups) { + return Err(Error::BadRequest(format!( + "Ruleset {ruleset} of {workspace_id} requires SSO: {email} signs in with a password, \ + so it cannot join this workspace" + ))); + } + Ok(()) +} + +/// Refuses giving `email` a password login while a `RequireSso` rule of a workspace they are a +/// non-service-account member of holds them. +pub async fn check_password_login_allowed( + conn: &mut sqlx::PgConnection, + email: &str, +) -> Result<()> { + let memberships = sqlx::query!( + r#"SELECT u.workspace_id, u.username, + COALESCE(array_agg(g.group_) FILTER (WHERE g.group_ IS NOT NULL), '{}') AS "groups!" + FROM usr u + LEFT JOIN usr_to_group g ON g.workspace_id = u.workspace_id AND g.usr = u.username + WHERE u.email = $1 AND NOT u.is_service_account + AND EXISTS (SELECT 1 FROM workspace_protection_rule r + WHERE r.workspace_id = u.workspace_id AND (r.rules & $2) <> 0) + GROUP BY u.workspace_id, u.username"#, + email, + ProtectionRules::REQUIRE_SSO.bits(), + ) + .fetch_all(&mut *conn) + .await?; + for m in memberships { + let rulesets = sso_rulesets(conn, &m.workspace_id).await?; + if let Some(ruleset) = sso_ruleset_holding(&rulesets, Some(&m.username), &m.groups) { + return Err(Error::BadRequest(format!( + "Ruleset {ruleset} of {} requires SSO for its members, so {email} cannot sign in \ + with a password", + m.workspace_id + ))); + } + } + Ok(()) +} + /// The roles members of `workspace_id` get in a fork of it, merged across its rulesets: where two /// rulesets map the same role, the first by name wins. Unmapped roles carry over unchanged. pub async fn fork_role_mapping( diff --git a/backend/windmill-common/tests/notify_events.rs b/backend/windmill-common/tests/notify_events.rs index 285086308e..a09bfc4115 100644 --- a/backend/windmill-common/tests/notify_events.rs +++ b/backend/windmill-common/tests/notify_events.rs @@ -375,8 +375,10 @@ async fn test_trigger_notify_user_email_change(db: Pool<Postgres>) { .await .expect("Should poll events"); assert!( - events.iter().any(|e| e.channel == "notify_user_email_change" - && e.payload == "test-workspace:test-user"), + events + .iter() + .any(|e| e.channel == "notify_user_email_change" + && e.payload == "test-workspace:test-user"), "email change should evict the key it moved" ); @@ -470,6 +472,75 @@ async fn test_trigger_notify_token_invalidation(db: Pool<Postgres>) { ); } +/// A token's `super_admin` follows its owner's down, judged at commit: the global user import +/// deletes and re-inserts every `password` row, which must leave a re-imported superadmin's +/// tokens alone. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_token_superadmin_follows_owner_demotion(db: Pool<Postgres>) { + let token_is_superadmin = || async { + sqlx::query_scalar::<_, bool>("SELECT super_admin FROM token WHERE token = 'SECRET_TOKEN'") + .fetch_one(&db) + .await + .unwrap() + }; + let reinsert = |super_admin: bool| { + let db = db.clone(); + async move { + let mut tx = db.begin().await.unwrap(); + sqlx::query("DELETE FROM password WHERE email = 'test@windmill.dev'") + .execute(&mut *tx) + .await + .unwrap(); + sqlx::query( + "INSERT INTO password(email, password_hash, login_type, super_admin, verified, name) + VALUES ('test@windmill.dev', 'x', 'password', $1, true, 'Test User')", + ) + .bind(super_admin) + .execute(&mut *tx) + .await + .unwrap(); + tx.commit().await.unwrap(); + } + }; + + reinsert(true).await; + assert!( + token_is_superadmin().await, + "re-imported superadmin keeps it" + ); + + // SCIM's rename moves the account and leaves its tokens under the old address. + for (from, to) in [ + ("test@windmill.dev", "renamed@windmill.dev"), + ("renamed@windmill.dev", "test@windmill.dev"), + ] { + sqlx::query("UPDATE password SET email = $1 WHERE email = $2") + .bind(to) + .bind(from) + .execute(&db) + .await + .unwrap(); + } + assert!( + token_is_superadmin().await, + "an email change is no demotion" + ); + + let before_id = get_latest_event_id(&db).await.unwrap(); + reinsert(false).await; + assert!( + !token_is_superadmin().await, + "re-imported as a user loses it" + ); + let events = poll_notify_events(&db, before_id).await.unwrap(); + assert!( + events + .iter() + .any(|e| e.channel == "notify_token_invalidation" && e.payload == "SECRET_TOK"), + "demotion should evict the cached identity, got {events:?}" + ); +} + #[sqlx::test(migrations = "../migrations", fixtures("base"))] async fn test_trigger_notify_webhook_change(db: Pool<Postgres>) { let before_id = get_latest_event_id(&db).await.unwrap(); diff --git a/backend/windmill-jseval/src/lib.rs b/backend/windmill-jseval/src/lib.rs index 9b87b28cbd..ad275b4625 100644 --- a/backend/windmill-jseval/src/lib.rs +++ b/backend/windmill-jseval/src/lib.rs @@ -128,6 +128,66 @@ fn add_closing_bracket(s: &str) -> String { s } +/// Characters a key needs to compare, choose or quote: an argument name holding them that is +/// also valid JavaScript is read as the expression. +#[cfg(feature = "quickjs")] +const CHOICE_CHARS: &[char] = &['"', '\'', '`', '\\', '?', '|', '&', '<', '>', '!']; + +/// The editors write `flow_input.<name>` for any argument name (`first name`, `customer:email`, +/// `amount (USD)`), which only this literal lookup resolves. It must not cover an expression +/// doing more than reading one (`flow_input.a == "x" ? b : c`, or `flow_input.a.b` reading into +/// an argument `a`): an argument named after the whole expression would replace its value. A +/// name that is not valid JavaScript after `flow_input.` cannot be such an expression. +fn is_literal_dot_key(key: &str, obj: Option<&HashMap<String, Box<RawValue>>>) -> bool { + let is_ident = |c: char| c.is_alphanumeric() || matches!(c, '_' | '$'); + if key.is_empty() { + return false; + } + if key.chars().all(is_ident) { + return true; + } + let (leading_name, rest) = key.split_at(key.find(|c: char| !is_ident(c)).unwrap_or(key.len())); + let reads_into_argument = + rest.starts_with('.') && obj.is_some_and(|obj| obj.contains_key(leading_name)); + #[cfg(feature = "quickjs")] + { + if !parses_as_expression(&format!("{FLOW_INPUT_PREFIX}.{key}")) { + return true; + } + !reads_into_argument && !key.contains(CHOICE_CHARS) && !key.contains("==") + } + #[cfg(not(feature = "quickjs"))] + { + const EXPRESSION_CHARS: &[char] = &[ + '"', '\'', '`', '\\', '?', ':', '(', ')', '[', ']', '{', '}', '=', '!', '<', '>', '|', + '&', ',', ';', + ]; + !key.contains(EXPRESSION_CHARS) && !reads_into_argument + } +} + +/// Whether `expr` compiles in either shape the evaluator runs it in: returned from an async +/// function, or as its body. Compiled as a module that is never evaluated, so nothing in it +/// runs; a failure to set up the check counts as compiling, the stricter answer. +#[cfg(feature = "quickjs")] +fn parses_as_expression(expr: &str) -> bool { + let Ok(runtime) = rquickjs::Runtime::new() else { + return true; + }; + let Ok(context) = rquickjs::Context::full(&runtime) else { + return true; + }; + // The line breaks keep a `//` in `expr` from commenting out the rest of the wrapper. + [ + format!("(async function() {{ return {expr}\n; }});"), + format!("(async function() {{ {expr}\n }});"), + ] + .into_iter() + .any(|source| { + context.with(|ctx| rquickjs::Module::declare(ctx, "flow_input_key", source).is_ok()) + }) +} + pub fn try_exact_property_access( expr: &str, flow_input: Option<&mappable_rc::Marc<HashMap<String, Box<RawValue>>>>, @@ -149,7 +209,7 @@ pub fn try_exact_property_access( let suffix = &expr[access_pattern_pos..]; let maybe_key_name = if suffix.starts_with(DOT_PATTERN) { let key_name_pos = DOT_PATTERN.len(); - Some(&suffix[key_name_pos..]) + Some(&suffix[key_name_pos..]).filter(|key| is_literal_dot_key(key, obj)) } else if suffix.starts_with(START_BRACKET_PATTERN) { let key_name_pos = START_BRACKET_PATTERN.len(); let suffix = &suffix[key_name_pos..]; @@ -161,7 +221,7 @@ pub fn try_exact_property_access( let end_key_name_pos = expr.len() - END_BRACKET_PATTERN.len(); &expr[start_key_name_pos..end_key_name_pos] }) - .filter(|s| s.len() > 0); + .filter(|s| s.len() > 0 && !s.contains(['"', '\\'])); flow_arg_name } else { None @@ -342,7 +402,7 @@ pub async fn eval_timeout_quickjs_within( // task" errors on subsequent requests from the main runtime. let handle = tokio::runtime::Handle::current(); let deadline = std::time::Instant::now() + timeout; - tokio::time::timeout( + let evaluated = tokio::time::timeout( timeout, tokio::task::spawn_blocking(move || { handle.block_on(async move { @@ -368,7 +428,29 @@ pub async fn eval_timeout_quickjs_within( "The expression evaluation `{expr}` took too long to execute (>{}ms)", timeout.as_millis() ) - })?? + })?; + evaluated?.map_err( + |e| match bracket_lookup_hint(&expr, flow_input.as_deref()) { + Some(hint) => anyhow::anyhow!("{e}. {hint}"), + None => e, + }, + ) +} + +/// For a failed `flow_input.<key>` whose `<key>` names an argument the literal lookup did not +/// take: how to read that argument. +#[cfg(feature = "quickjs")] +fn bracket_lookup_hint( + expr: &str, + flow_input: Option<&HashMap<String, Box<RawValue>>>, +) -> Option<String> { + let key = expr + .strip_prefix(FLOW_INPUT_PREFIX)? + .strip_prefix(DOT_PATTERN)?; + flow_input?.contains_key(key).then(|| { + let quoted = serde_json::to_string(key).unwrap_or_default(); + format!("The flow has an argument named {quoted}: read it with flow_input[{quoted}].") + }) } /// Default memory cap, in bytes, for a single flow step-input transform eval @@ -1347,6 +1429,62 @@ mod tests { assert_eq!(result.unwrap().get(), "\"production\""); } + #[test] + fn test_try_exact_property_access_only_reads_one_argument() { + let expr_key = r#"region == "eu" ? "a" : "b""#; + let bracket_key = r#"x"] || flow_input["y"#; + let mut fi = HashMap::new(); + for key in [ + expr_key, + bracket_key, + "first name", + "my-arg", + "customer.email", + "pinned", + "pinned.field", + "first", + "customer:email", + "amount (USD)", + "a=b", + "amount", + "my", + ] { + fi.insert(key.to_string(), to_raw_value(&json!("argument"))); + } + let fi = mappable_rc::Marc::new(fi); + + for expr in [ + format!("flow_input.{expr_key}"), + format!("flow_input[\"{bracket_key}\"]"), + "flow_input.pinned.field".to_string(), + ] { + assert!(try_exact_property_access(&expr, Some(&fi), None).is_none()); + } + for expr in [ + "flow_input.first name", + "flow_input.my-arg", + "flow_input.customer.email", + "flow_input.customer:email", + "flow_input.amount (USD)", + "flow_input.a=b", + ] { + assert!( + try_exact_property_access(expr, Some(&fi), None).is_some(), + "{expr}" + ); + } + } + + #[test] + fn test_parses_as_expression() { + assert!(parses_as_expression( + r#"flow_input.region == "eu" ? "a" : "b""# + )); + assert!(parses_as_expression("flow_input.amount (USD)")); + assert!(!parses_as_expression("flow_input.customer:email")); + assert!(!parses_as_expression("flow_input.first name")); + } + #[test] fn test_try_exact_property_access_missing_key() { let fi = mappable_rc::Marc::new(HashMap::new()); @@ -1399,6 +1537,27 @@ mod tests { assert_eval("obj['name']", env.clone(), json!("test")).await; } + #[tokio::test] + async fn test_failed_dot_lookup_names_the_bracket_form() { + let fi = mappable_rc::Marc::new(HashMap::from([( + "a=b".to_string(), + to_raw_value(&json!("argument")), + )])); + let err = eval_timeout_quickjs( + "flow_input.a=b".to_string(), + HashMap::new(), + Some(fi), + None, + None, + None, + None, + ) + .await + .unwrap_err() + .to_string(); + assert!(err.contains(r#"read it with flow_input["a=b"]"#), "{err}"); + } + // ===================================================================== // ARRAY OPERATIONS // ===================================================================== @@ -3145,7 +3304,9 @@ mod tests { Some(deadline), ) .await; - let err = err.expect_err("an endless script must be interrupted").to_string(); + let err = err + .expect_err("an endless script must be interrupted") + .to_string(); assert!(err.contains("took too long"), "unexpected error: {err}"); } diff --git a/backend/windmill-mcp/src/client_registration.rs b/backend/windmill-mcp/src/client_registration.rs index 1500d21e24..8cddf8e191 100644 --- a/backend/windmill-mcp/src/client_registration.rs +++ b/backend/windmill-mcp/src/client_registration.rs @@ -23,6 +23,11 @@ use crate::oauth::{no_redirect_http_client_pinned, AuthorizationManager}; pub struct McpClientCredentials { pub client_id: String, pub client_secret: Option<String>, + /// Whether this call registered (or re-registered) Windmill at the server + /// rather than reusing the stored client. Registration makes the server + /// contact an author-chosen host and writes the instance-wide + /// `mcp_oauth_client` table, so callers acting for a user audit it. + pub newly_registered: bool, /// The token endpoint and the addresses it resolved to during SSRF validation. /// Both are private so that [`Self::token_request`] is the only way to obtain /// the URL: it returns it together with a client pinned to those addresses, so @@ -175,6 +180,7 @@ pub async fn get_or_refresh_mcp_client( return Ok(McpClientCredentials { client_id: client.client_id, client_secret: decrypted_secret, + newly_registered: false, token_endpoint: client.token_endpoint, token_endpoint_target, }); @@ -261,6 +267,7 @@ pub async fn get_or_refresh_mcp_client( Ok(McpClientCredentials { client_id, client_secret, + newly_registered: true, token_endpoint: metadata.token_endpoint, token_endpoint_target, }) @@ -311,6 +318,7 @@ mod tests { let credentials = McpClientCredentials { client_id: "id".to_string(), client_secret: None, + newly_registered: false, token_endpoint: "http://unresolvable.invalid/token".to_string(), token_endpoint_target: windmill_common::ssrf::ValidatedTarget { host: "unresolvable.invalid".to_string(), diff --git a/backend/windmill-mcp/src/common/types.rs b/backend/windmill-mcp/src/common/types.rs index 7d91e94255..2b902a4d18 100644 --- a/backend/windmill-mcp/src/common/types.rs +++ b/backend/windmill-mcp/src/common/types.rs @@ -28,9 +28,14 @@ pub struct MultiWorkspaceMcp; pub struct NoEndpointTools; /// Raw bearer token wrapper for Axum extensions. In multi-workspace mode the -/// runner needs the raw token to re-resolve auth for each requested workspace. +/// runner needs the raw token to re-resolve auth for each requested workspace, +/// and the request's client address, which an IP-restricted token is checked +/// against on every resolution. #[derive(Clone, Debug)] -pub struct McpToken(pub String); +pub struct McpToken { + pub token: String, + pub client_ip: Option<std::net::IpAddr>, +} /// Summary of a workspace the caller can access, returned by the /// `list_workspaces` tool in multi-workspace mode. diff --git a/backend/windmill-mcp/src/server/backend.rs b/backend/windmill-mcp/src/server/backend.rs index 1dd746a2b7..5938b4c9c5 100644 --- a/backend/windmill-mcp/src/server/backend.rs +++ b/backend/windmill-mcp/src/server/backend.rs @@ -10,7 +10,8 @@ use serde_json::Value; use std::collections::HashMap; use crate::common::types::{ - FlowInfo, HubScriptInfo, ResourceInfo, ResourceType, SchemaType, ScriptInfo, WorkspaceInfo, + FlowInfo, HubScriptInfo, McpToken, ResourceInfo, ResourceType, SchemaType, ScriptInfo, + WorkspaceInfo, }; use crate::server::endpoints::EndpointTool; @@ -255,7 +256,7 @@ pub trait McpBackend: Send + Sync + Clone + 'static { /// calls (the base auth carries no workspace-specific permissions). async fn resolve_workspace_auth( &self, - token: &str, + token: &McpToken, workspace_id: &str, ) -> BackendResult<Self::Auth>; diff --git a/backend/windmill-mcp/src/server/runner.rs b/backend/windmill-mcp/src/server/runner.rs index 6af8eebc1b..0b1d17c2c7 100644 --- a/backend/windmill-mcp/src/server/runner.rs +++ b/backend/windmill-mcp/src/server/runner.rs @@ -160,7 +160,7 @@ pub(super) enum McpMode { /// The token has no bound workspace (`workspace_id IS NULL`). Tools take an /// explicit `workspace_id` argument; the wrapped value is the raw bearer /// token, used to re-resolve auth per requested workspace. - Multi(String), + Multi(McpToken), } /// Everything a request carries besides its MCP payload. @@ -207,7 +207,7 @@ impl<B: McpBackend> Runner<B> { tracing::error!("MultiWorkspaceMcp set but McpToken missing"); ErrorData::internal_error("MCP token not found for multi-workspace session", None) })?; - McpMode::Multi(token.0.clone()) + McpMode::Multi(token.clone()) } else { let workspace_id = http_parts .extensions @@ -1094,6 +1094,29 @@ impl<B: McpBackend> Runner<B> { } }; + // A token narrower than `mcp:all` reaches the Hub scripts its `mcp:hub:` apps list. + if is_hub && !scope_config.all { + let listed = match scope_config.hub_apps.as_deref() { + Some(apps) => self + .backend + .list_hub_scripts(Some(apps)) + .await + .map_err(|e| ErrorData::internal_error(e.message, None))? + .iter() + .any(|s| s.version_id.to_string() == path), + None => false, + }; + if !listed { + return Err(ErrorData::invalid_params( + format!( + "Hub tool '{name}' is not in this token's selection. Add mcp:hub:<app> \ + (e.g. mcp:hub:slack) or use mcp:all." + ), + None, + )); + } + } + // Validate script/flow scope if !is_hub && scope_config.granular { if tool_type == "script" && !scope_config.is_allowed("script", &path) { @@ -1204,7 +1227,7 @@ impl<B: McpBackend> Runner<B> { async fn call_tool_multi( &self, base_auth: &B::Auth, - token: &str, + token: &McpToken, scope_config: &crate::common::scope::McpScopeConfig, read_only: bool, name: std::borrow::Cow<'static, str>, diff --git a/backend/windmill-native-triggers/src/github/external.rs b/backend/windmill-native-triggers/src/github/external.rs index 6e34154df3..51c705cf29 100644 --- a/backend/windmill-native-triggers/src/github/external.rs +++ b/backend/windmill-native-triggers/src/github/external.rs @@ -302,7 +302,15 @@ impl External for GitHub { .cloned() .unwrap_or_default(); - let payload: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); + let mut payload: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); + // GitHub echoes the hook's own delivery URL (ping and meta events), which carries the + // token Windmill registered for it; the run's arguments are readable by every viewer. + if let Some(config) = payload + .pointer_mut("/hook/config") + .and_then(|config| config.as_object_mut()) + { + config.remove("url"); + } args.insert( "event".to_string(), diff --git a/backend/windmill-native-triggers/src/handler.rs b/backend/windmill-native-triggers/src/handler.rs index 29da79647c..ebaddc82da 100644 --- a/backend/windmill-native-triggers/src/handler.rs +++ b/backend/windmill-native-triggers/src/handler.rs @@ -17,13 +17,14 @@ use serde::{Deserialize, Serialize}; use sqlx::PgConnection; use std::sync::Arc; use windmill_api_auth::{ - build_scope_path_filter, check_scopes, create_token_internal, require_is_writer, ApiAuthed, - NewToken, + build_scope_path_filter, check_run_scopes, check_scopes, create_token_internal, + require_is_writer, ApiAuthed, NewToken, }; use windmill_audit::{audit_oss::audit_log, ActionKind}; use windmill_common::{ db::UserDB, error::{Error, JsonResult, Result}, + runnable_ref::RunnableRef, DB, }; @@ -165,6 +166,10 @@ async fn create_native_trigger<T: External>( check_scopes(&authed, || { format!("native_triggers:write:{}", &data.script_path) })?; + check_run_scopes( + &authed, + &[RunnableRef::from_path(&data.script_path, data.is_flow)?], + )?; require_is_writer_on_runnable( &authed, &data.script_path, @@ -303,6 +308,10 @@ async fn update_native_trigger_handler<T: External>( check_scopes(&authed, || { format!("native_triggers:write:{}", &data.script_path) })?; + check_run_scopes( + &authed, + &[RunnableRef::from_path(&data.script_path, data.is_flow)?], + )?; require_is_writer_on_runnable( &authed, &data.script_path, diff --git a/backend/windmill-native-triggers/src/lib.rs b/backend/windmill-native-triggers/src/lib.rs index eb13bf9a28..672b2d376b 100644 --- a/backend/windmill-native-triggers/src/lib.rs +++ b/backend/windmill-native-triggers/src/lib.rs @@ -43,20 +43,16 @@ use serde_json::value::RawValue; use sqlx::{FromRow, PgConnection, Postgres}; use std::{collections::HashMap, fmt::Debug}; use strum::{EnumIter, IntoEnumIterator}; -use tokio::task; use windmill_common::{ db::UserDB, error::{to_anyhow, Error, Result}, triggers::TriggerKind, utils::HTTP_CLIENT, - variables::{build_crypt, decrypt, encrypt}, + variables::{build_crypt, decrypt}, DB, }; use windmill_queue::PushArgsOwned; -#[cfg(feature = "native_trigger")] -use windmill_oauth::{ErrorField, ExecuteError, OClient, RefreshToken, Url, OAUTH_HTTP_CLIENT}; - use windmill_api_auth::{ApiAuthed, ScopePathFilter}; pub mod handler; pub(crate) mod lock; @@ -429,8 +425,10 @@ pub trait External: Send + Sync + 'static { Some(connection_path), ) .await?; + let client = client_for(&oauth_config, url, Self::DISPLAY_NAME).await?; let result = make_http_request( + &client, url, method.clone(), headers.clone(), @@ -451,25 +449,19 @@ pub trait External: Send + Sync + 'static { Self::DISPLAY_NAME ); - let access_token = refresh_connection( - db, - workspace_id, - &oauth_config, - Self::REFRESH_ENDPOINT, - Self::AUTH_ENDPOINT, - ) - .await - .map_err(|f| { - self.external_error( - f.rejected.then_some(StatusCode::UNAUTHORIZED), - format!( - "the stored credentials could not be refreshed: {}", - f.message - ), - ) - })?; + let access_token = refresh_connection(db, workspace_id, &oauth_config) + .await + .map_err(|f| { + self.external_error( + f.rejected.then_some(StatusCode::UNAUTHORIZED), + format!( + "the stored credentials could not be refreshed: {}", + f.message + ), + ) + })?; - make_http_request(url, method, headers, body.as_ref(), &access_token) + make_http_request(&client, url, method, headers, body.as_ref(), &access_token) .await .map_err(|e| self.external_api_error(e)) } @@ -487,6 +479,14 @@ pub trait External: Send + Sync + 'static { .unwrap_or_else(|| body.to_string()), self.is_transient_response(*status, body), ), + HttpRequestError::Redirect { location, .. } => ( + format!( + "{} answered with a redirect to {location}; redirects are not followed, so \ + set the resource's baseUrl to the final address.", + Self::DISPLAY_NAME + ), + false, + ), // A reqwest error names the request it was making, never why it failed: the reason // (refused, DNS, TLS) lives one link down the source chain. other => (error_source_chain(other), false), @@ -594,23 +594,78 @@ pub struct OAuthConfig { pub base_url: String, pub access_token: String, pub refresh_token: Option<String>, - pub client_id: String, - pub client_secret: String, pub connection_path: String, pub account_id: Option<i32>, - /// Made by the connect flow, so refreshed with the client above. + /// Issued by the workspace's OAuth app, whose server a Nextcloud resource saved without its + /// own `baseUrl` belongs to. #[serde(default)] pub managed: bool, + /// `base_url` is the server an admin configured for the workspace's or the instance's client. + #[serde(default)] + pub base_url_configured: bool, +} + +const ALLOW_PRIVATE_NEXTCLOUD_URLS_ENV: &str = "ALLOW_PRIVATE_NEXTCLOUD_URLS"; + +lazy_static::lazy_static! { + /// Private Nextcloud servers a connection's resource may name, as a host, host:port or + /// CIDR list (`true` for every private host), like the other `ALLOW_PRIVATE_*` settings. + static ref ALLOW_PRIVATE_NEXTCLOUD_URLS: windmill_common::ssrf::PrivateHostAllowance = + windmill_common::ssrf::PrivateHostAllowance::from_env(ALLOW_PRIVATE_NEXTCLOUD_URLS_ENV); +} + +/// The client for a call to `url`. A server only a connection's resource names may be anyone's +/// choice, so it must be public or allowed by `ALLOW_PRIVATE_NEXTCLOUD_URLS`, is connected to at +/// the address that was checked, and may not redirect elsewhere. The server an admin configured +/// as the client's needs neither. +async fn client_for( + oauth_config: &OAuthConfig, + url: &str, + display_name: &str, +) -> Result<std::borrow::Cow<'static, reqwest::Client>> { + if oauth_config.base_url.is_empty() || oauth_config.base_url_configured { + return Ok(std::borrow::Cow::Borrowed(&*HTTP_CLIENT)); + } + let target = + windmill_common::ssrf::validate_url_for_ssrf_allowing(url, &ALLOW_PRIVATE_NEXTCLOUD_URLS) + .await + .map_err(|e| { + let hint = match e { + windmill_common::ssrf::SsrfValidationError::Private { .. } => format!( + " To use a server on a private network, configure it as the \ + {display_name} integration's server (workspace settings → Integration \ + triggers, or instance settings → OAuth), or add its host (host, \ + host:port or CIDR range) to the comma-separated \ + {ALLOW_PRIVATE_NEXTCLOUD_URLS_ENV} environment variable." + ), + _ => String::new(), + }; + Error::BadRequest(format!( + "The {display_name} server {} cannot be used: {e}.{hint}", + oauth_config.base_url + )) + })?; + let client = target + .apply_dns_pinning(windmill_common::utils::configure_client( + reqwest::ClientBuilder::new(), + )) + .user_agent("windmill/beta") + .redirect(reqwest::redirect::Policy::none()) + .timeout(std::time::Duration::from_secs(20)) + .connect_timeout(std::time::Duration::from_secs(10)) + .build() + .map_err(|e| Error::internal_err(format!("building the {display_name} client: {e}")))?; + Ok(std::borrow::Cow::Owned(client)) } pub async fn make_http_request<T: DeserializeOwned + Send, B: Serialize>( + client: &reqwest::Client, url: &str, method: Method, headers: Option<HashMap<String, String>>, body: Option<&B>, access_token: &str, ) -> std::result::Result<T, HttpRequestError> { - let client = &*HTTP_CLIENT; let mut request = client.request(method, url); request = request @@ -633,6 +688,14 @@ pub async fn make_http_request<T: DeserializeOwned + Send, B: Serialize>( let response = request.send().await?; let status = response.status(); + if status.is_redirection() { + let location = response + .headers() + .get(reqwest::header::LOCATION) + .map(|l| String::from_utf8_lossy(l.as_bytes()).into_owned()) + .unwrap_or_else(|| "an unnamed address".to_string()); + return Err(HttpRequestError::Redirect { status, location }); + } let bytes = response.bytes().await?; if !status.is_success() { @@ -653,6 +716,8 @@ pub enum HttpRequestError { Reqwest(reqwest::Error), Json(serde_json::Error), ApiError { status: StatusCode, body: String }, + /// Only reached on a client that does not follow redirects. + Redirect { status: StatusCode, location: String }, } impl std::fmt::Display for HttpRequestError { @@ -663,6 +728,9 @@ impl std::fmt::Display for HttpRequestError { HttpRequestError::ApiError { status, body } => { write!(f, "HTTP {} error: {}", status.as_u16(), body) } + HttpRequestError::Redirect { status, location } => { + write!(f, "HTTP {} redirect to {}", status.as_u16(), location) + } } } } @@ -672,7 +740,7 @@ impl std::error::Error for HttpRequestError { match self { HttpRequestError::Reqwest(e) => Some(e), HttpRequestError::Json(e) => Some(e), - HttpRequestError::ApiError { .. } => None, + HttpRequestError::ApiError { .. } | HttpRequestError::Redirect { .. } => None, } } } @@ -688,7 +756,8 @@ impl HttpRequestError { match self { HttpRequestError::Reqwest(e) => e.status(), HttpRequestError::Json(_) => None, - HttpRequestError::ApiError { status, .. } => Some(*status), + HttpRequestError::ApiError { status, .. } + | HttpRequestError::Redirect { status, .. } => Some(*status), } } } @@ -792,6 +861,30 @@ pub(crate) fn instance_base_url(entry: &serde_json::Value) -> String { } } +/// Whether `base_url` is the server of the workspace's or the instance's client, both set by an +/// admin, rather than one a connection's resource names. +async fn is_admin_configured_base_url( + db: &DB, + workspace_id: &str, + service_name: ServiceName, + base_url: &str, +) -> Result<bool> { + let base_url = base_url.trim_end_matches('/'); + let same = |url: &str| url.trim_end_matches('/') == base_url; + // No integration (or failing to read it) leaves the server to the stricter check. + if let Ok(integration) = get_workspace_integration(db, workspace_id, service_name).await { + if integration.oauth_data["base_url"] + .as_str() + .is_some_and(same) + { + return Ok(true); + } + } + Ok(instance_oauth_entry(db, service_name) + .await? + .is_some_and(|entry| same(&instance_base_url(&entry)))) +} + /// Assemble the credentials of one connection: the resource of the service's type at /// `connection_path` and the token variable at the same path. /// @@ -847,61 +940,35 @@ pub async fn decrypt_oauth_data<T: DeserializeOwned>( }; let managed = row.managed.unwrap_or(false); - let (base_url, client_id, client_secret) = if managed { - let oauth_data = get_workspace_integration(db, workspace_id, service_name) + // Only Nextcloud has a base URL: the resource's own, else the server of the client that issued + // the account. + let base_url = match row + .resource_value + .as_ref() + .and_then(|v| v.get("baseUrl")) + .and_then(|v| v.as_str()) + { + Some(url) if !url.is_empty() => url.trim_end_matches('/').to_string(), + _ if managed => get_workspace_integration(db, workspace_id, service_name) .await? - .oauth_data; - let (client_id, client_secret) = if oauth_data - .get("instance_shared") - .and_then(|v| v.as_bool()) - .unwrap_or(false) - { - windmill_common::global_settings::get_instance_oauth_credentials( - db, - service_name.resource_type(), - ) - .await - .map_err(|e| { - Error::InternalErr(format!( - "Failed to read instance OAuth credentials for {}: {}", - service_name, e - )) - })? - } else { - ( - oauth_data["client_id"].as_str().unwrap_or("").to_string(), - oauth_data["client_secret"] - .as_str() - .unwrap_or("") - .to_string(), - ) - }; - let base_url = oauth_data["base_url"].as_str().unwrap_or("").to_string(); - (base_url, client_id, client_secret) - } else { - // Only Nextcloud has a base URL: the resource's own, else the instance client's server. - let base_url = match row - .resource_value - .as_ref() - .and_then(|v| v.get("baseUrl")) - .and_then(|v| v.as_str()) - { - Some(url) if !url.is_empty() => url.trim_end_matches('/').to_string(), - _ if service_name == ServiceName::Nextcloud => instance_oauth_entry(db, service_name) - .await? - .map(|e| instance_base_url(&e)) - .unwrap_or_default(), - _ => String::new(), - }; - (base_url, String::new(), String::new()) + .oauth_data["base_url"] + .as_str() + .unwrap_or("") + .to_string(), + _ if service_name == ServiceName::Nextcloud => instance_oauth_entry(db, service_name) + .await? + .map(|e| instance_base_url(&e)) + .unwrap_or_default(), + _ => String::new(), }; + let base_url_configured = !base_url.is_empty() + && is_admin_configured_base_url(db, workspace_id, service_name, &base_url).await?; let assembled = json!({ "base_url": base_url, + "base_url_configured": base_url_configured, "access_token": access_token, "refresh_token": row.refresh_token, - "client_id": client_id, - "client_secret": client_secret, "connection_path": connection_path, "account_id": row.account_id, "managed": managed, @@ -911,14 +978,6 @@ pub async fn decrypt_oauth_data<T: DeserializeOwned>( .map_err(|e| Error::InternalErr(format!("Failed to deserialize OAuth data: {}", e))) } -/// Token refresh response -#[cfg(feature = "native_trigger")] -#[derive(Debug, Deserialize)] -struct RefreshTokenResponse { - access_token: String, - refresh_token: Option<String>, -} - /// Why an OAuth token refresh did not produce a new token. #[derive(Debug)] pub struct RefreshFailure { @@ -942,135 +1001,20 @@ impl RefreshFailure { } } -/// Whether a token endpoint's answer means reconnecting the integration is the fix, rather -/// than the endpoint failing to serve a grant that may well be valid. -/// -/// Used when the answer carried no OAuth error code to read. The body is checked because no -/// status reliably reports a refusal: GitHub answers `bad_refresh_token` with HTTP 200. The -/// status is the last resort — on a token endpoint these three most often mean the stored -/// grant is spent, and there is nothing better to go on. -pub fn grant_refused(status: Option<StatusCode>, body: &str) -> bool { - body.contains("invalid_grant") - || body.contains("bad_refresh_token") - || matches!( - status, - Some(StatusCode::BAD_REQUEST | StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) - ) -} - -/// Whether an OAuth error code (RFC 6749 §5.2) means the credentials Windmill stored are what -/// needs replacing. The rest — a malformed request, an unsupported grant type, a scope the -/// server will not grant — are faults in how the integration asks, which reconnecting as the -/// same user will reproduce exactly. -#[cfg(feature = "native_trigger")] -fn code_means_reconnect(code: &ErrorField) -> bool { - matches!(code, ErrorField::InvalidGrant | ErrorField::InvalidClient) -} - -#[cfg(feature = "native_trigger")] -fn refresh_failure_from(e: ExecuteError) -> RefreshFailure { - let rejected = match &e { - // A code says exactly what was refused, so nothing else needs guessing at. - ExecuteError::ErrorResponse { error, .. } => code_means_reconnect(&error.error), - // A body that would not deserialize is where a refusal hides when the status says - // nothing, and it is the only place the reason is written down. - ExecuteError::BadResponse { status, body, .. } => { - grant_refused(Some(*status), &String::from_utf8_lossy(body)) - } - _ => grant_refused(e.status(), ""), - }; - let message = match &e { - ExecuteError::BadResponse { body, .. } => { - format!("{e}: {}", String::from_utf8_lossy(body)) - } - _ => error_source_chain(&e), - }; - if rejected { - RefreshFailure::rejected(message) - } else { - RefreshFailure::outage(message) - } -} - -/// Refresh OAuth tokens using windmill-oauth. -#[cfg(feature = "native_trigger")] -pub async fn refresh_oauth_tokens( - oauth_config: &OAuthConfig, - refresh_endpoint: &str, - auth_endpoint: &str, -) -> std::result::Result<OAuthConfig, RefreshFailure> { - let refresh_token_str = oauth_config - .refresh_token - .as_ref() - .ok_or_else(|| RefreshFailure::rejected("no refresh token is stored".to_string()))?; - - // Build OAuth client for token refresh - // Auth URL is not used for refresh, but required by the client constructor - let auth_url = Url::parse(&resolve_endpoint(&oauth_config.base_url, auth_endpoint)) - .map_err(|e| RefreshFailure::outage(format!("invalid auth URL: {e}")))?; - let token_url = Url::parse(&resolve_endpoint(&oauth_config.base_url, refresh_endpoint)) - .map_err(|e| RefreshFailure::outage(format!("invalid token URL: {e}")))?; - - let mut client = OClient::new(oauth_config.client_id.clone(), auth_url, token_url); - client.set_client_secret(oauth_config.client_secret.clone()); - - let token_response: RefreshTokenResponse = client - .exchange_refresh_token(&RefreshToken::from(refresh_token_str.as_str())) - .with_client(&*OAUTH_HTTP_CLIENT) - .execute() - .await - .map_err(refresh_failure_from)?; - - Ok(OAuthConfig { - base_url: oauth_config.base_url.clone(), - access_token: token_response.access_token, - refresh_token: token_response - .refresh_token - .or_else(|| oauth_config.refresh_token.clone()), - client_id: oauth_config.client_id.clone(), - client_secret: oauth_config.client_secret.clone(), - connection_path: oauth_config.connection_path.clone(), - account_id: oauth_config.account_id, - managed: oauth_config.managed, - }) -} - -/// Mint a new access token for a connection the service refused. A connect-flow account refreshes -/// with the client `decrypt_oauth_data` read; a connected resource's account through the variable -/// store, which knows the instance client that issued it. +/// Mint a new access token for a connection the service refused, through the variable store: it +/// knows the client that issued the account (a workspace app included) and writes the token where +/// the variable keeps it, an external secret backend included. async fn refresh_connection( db: &DB, workspace_id: &str, oauth_config: &OAuthConfig, - refresh_endpoint: &str, - auth_endpoint: &str, ) -> std::result::Result<String, RefreshFailure> { let Some(account_id) = oauth_config.account_id else { return Err(RefreshFailure::rejected( "the connection has no refresh token; reconnect it".to_string(), )); }; - if !oauth_config.managed { - return refresh_resource_account(db, workspace_id, oauth_config, account_id).await; - } - let refreshed = refresh_oauth_tokens(oauth_config, refresh_endpoint, auth_endpoint).await?; - task::spawn({ - let db = db.clone(); - let workspace_id = workspace_id.to_string(); - let access_token = refreshed.access_token.clone(); - let refresh_token = refreshed.refresh_token.clone(); - async move { - update_oauth_token_resource( - &db, - &workspace_id, - account_id, - &access_token, - refresh_token.as_deref(), - ) - .await; - } - }); - Ok(refreshed.access_token) + refresh_resource_account(db, workspace_id, oauth_config, account_id).await } #[cfg(feature = "native_trigger")] @@ -1106,76 +1050,6 @@ async fn refresh_resource_account( )) } -/// Fallback refresh without native_triggers feature -#[cfg(not(feature = "native_trigger"))] -pub async fn refresh_oauth_tokens( - _oauth_config: &OAuthConfig, - _refresh_endpoint: &str, - _auth_endpoint: &str, -) -> std::result::Result<OAuthConfig, RefreshFailure> { - Err(RefreshFailure { - rejected: false, - message: "the native_trigger feature is not enabled".to_string(), - }) -} - -/// Write a refreshed token back to the account it was refreshed from, by that account's id, never -/// by service or path: several connections share a service, and a connection's path can be -/// reconnected or renamed while the refresh is in flight. A provider that rotates refresh tokens -/// invalidates the old one, so writing it onto another account would break that account's next -/// refresh. -/// -/// No authorization happens here: it overwrites the account's secrets as the server. Call it only -/// with tokens just refreshed from that account's own refresh token. -pub async fn update_oauth_token_resource( - db: &DB, - workspace_id: &str, - account_id: i32, - new_access_token: &str, - new_refresh_token: Option<&str>, -) { - let result = async { - let mc = build_crypt(db, workspace_id).await?; - let encrypted_token = encrypt(&mc, new_access_token); - - sqlx::query!( - "UPDATE variable SET value = $1 WHERE workspace_id = $2 AND account = $3", - encrypted_token, - workspace_id, - account_id, - ) - .execute(db) - .await?; - - // Even without a new refresh token, expires_at moves so the background refresh does not - // re-refresh immediately. - sqlx::query!( - "UPDATE account SET - refresh_token = COALESCE($1, refresh_token), - expires_at = now() + interval '1 hour', - refresh_error = NULL - WHERE workspace_id = $2 AND id = $3", - new_refresh_token, - workspace_id, - account_id, - ) - .execute(db) - .await?; - - Ok::<(), Error>(()) - } - .await; - - if let Err(e) = result { - tracing::error!( - "Failed to update OAuth tokens of account {} in workspace {}: {}", - account_id, - workspace_id, - e - ); - } -} - /// The scopes a webhook token must carry to run one runnable, and nothing else. /// /// Always derived from the runnable the trigger points at *now*. A token that outlives a rename @@ -1206,7 +1080,8 @@ pub async fn rotate_webhook_token( use windmill_common::utils::rd_string; let old = match sqlx::query!( - "SELECT email, workspace_id, super_admin, owner FROM token WHERE token_hash = $1", + "SELECT email, workspace_id, super_admin, owner, allowed_ips::text[] AS allowed_ips, admin + FROM token WHERE token_hash = $1", old_token_hash ) .fetch_optional(db) @@ -1237,8 +1112,8 @@ pub async fn rotate_webhook_token( .map(|d| Utc::now() + d); sqlx::query!( - "INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin, scopes, workspace_id, owner, expiration) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)", + "INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin, scopes, workspace_id, owner, expiration, allowed_ips, admin) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::text[]::cidr[], $12)", new_hash, new_prefix, plaintext as Option<&str>, @@ -1249,6 +1124,8 @@ pub async fn rotate_webhook_token( old.workspace_id, old.owner, new_expiration, + old.allowed_ips.as_deref(), + old.admin, ) .execute(db) .await?; @@ -1871,8 +1748,6 @@ pub struct Connection { pub owner: Option<String>, /// The workspace connection, which every member may use. pub workspace: bool, - /// Made by the integration trigger connect flow, rather than a resource connected elsewhere. - pub managed: bool, /// The scopes requested when the account was connected; unknown when absent. pub scopes: Option<Vec<String>>, /// The scopes this service's triggers need that `scopes` lacks; unknown when absent. @@ -1891,8 +1766,7 @@ pub async fn list_usable_connections( ) -> Result<Vec<Connection>> { let mut connections = sqlx::query_as!( Connection, - r#"SELECT v.path, r.created_by AS "owner?", false AS "workspace!", - COALESCE(a.is_workspace_integration, false) AS "managed!", a.scopes AS "scopes?", + r#"SELECT v.path, r.created_by AS "owner?", false AS "workspace!", a.scopes AS "scopes?", NULL::text[] AS "missing_scopes?" FROM variable v JOIN resource r ON r.workspace_id = v.workspace_id AND r.path = v.path @@ -1942,8 +1816,7 @@ pub async fn workspace_connection( ) -> Result<Option<Connection>> { let connection = sqlx::query_as!( Connection, - r#"SELECT v.path, r.created_by AS "owner?", true AS "workspace!", - COALESCE(a.is_workspace_integration, false) AS "managed!", a.scopes AS "scopes?", + r#"SELECT v.path, r.created_by AS "owner?", true AS "workspace!", a.scopes AS "scopes?", NULL::text[] AS "missing_scopes?" FROM workspace_integrations wi JOIN variable v ON v.workspace_id = wi.workspace_id AND v.path = wi.resource_path diff --git a/backend/windmill-native-triggers/src/workspace_integrations.rs b/backend/windmill-native-triggers/src/workspace_integrations.rs index 80cda6b70d..1bc15d3fcc 100644 --- a/backend/windmill-native-triggers/src/workspace_integrations.rs +++ b/backend/windmill-native-triggers/src/workspace_integrations.rs @@ -24,7 +24,6 @@ use windmill_common::{ db::UserDB, error::{Error, JsonResult, Result}, utils::{require_admin, HTTP_CLIENT}, - variables::{build_crypt, encrypt}, DB, }; @@ -35,7 +34,7 @@ use windmill_api_auth::{check_scopes, require_is_writer, ApiAuthed}; use crate::{ decrypt_oauth_data, delete_token_by_hash, delete_workspace_integration, instance_base_url, instance_oauth_entry, list_usable_connections, lock_connection, nextcloud::OcsResponse, - require_native_integration_use, resolve_endpoint, Connection, ServiceName, + resolve_endpoint, Connection, ServiceName, }; #[cfg(feature = "native_trigger")] @@ -60,17 +59,15 @@ type HmacSha256 = Hmac<Sha256>; const STATE_EXPIRATION_SECONDS: i64 = 600; // 10 minutes /// Generate a signed OAuth state that is cluster-safe. -/// The state contains: workspace_id, service_name, timestamp, nonce, the path the connection -/// will be saved at, and the user it was issued to. The path makes the callback independent of the -/// page the provider redirects to; the user stops anyone else from finishing the flow, which would -/// save their account at a path the issuer chose. +/// The state contains: workspace_id, service_name, timestamp, nonce and the user it was issued to. +/// The workspace and service make the callback independent of the page the provider redirects to; +/// the user stops anyone else from exchanging the code, which would hand them the issuer's token. /// It's signed with HMAC-SHA256 using the workspace key. #[cfg(feature = "native_trigger")] async fn generate_signed_state( db: &DB, workspace_id: &str, service_name: ServiceName, - connection_path: &str, username: &str, ) -> Result<String> { use windmill_common::variables::get_workspace_key; @@ -78,12 +75,11 @@ async fn generate_signed_state( let nonce = uuid::Uuid::new_v4().to_string(); let timestamp = chrono::Utc::now().timestamp(); let payload = format!( - "{}:{}:{}:{}:{}:{}", + "{}:{}:{}:{}:{}", workspace_id, service_name.as_str(), timestamp, nonce, - URL_SAFE_NO_PAD.encode(connection_path), URL_SAFE_NO_PAD.encode(username) ); @@ -101,8 +97,7 @@ async fn generate_signed_state( Ok(format!("{}:{}", encoded_payload, encoded_signature)) } -/// Validate a signed OAuth state (correct signature, workspace, service and user, not expired) -/// and return the connection path it was issued for. +/// Validate a signed OAuth state: correct signature, workspace, service and user, not expired. #[cfg(feature = "native_trigger")] async fn validate_signed_state( db: &DB, @@ -110,7 +105,7 @@ async fn validate_signed_state( workspace_id: &str, service_name: ServiceName, username: &str, -) -> Result<String> { +) -> Result<()> { use windmill_common::variables::get_workspace_key; let invalid = || Error::BadRequest("Invalid or expired state parameter".to_string()); @@ -123,13 +118,12 @@ async fn validate_signed_state( .and_then(|bytes| String::from_utf8(bytes).ok()) .ok_or_else(invalid)?; - // Parse payload: workspace_id:service_name:timestamp:nonce:connection_path:username - let [state_workspace_id, state_service, timestamp, _nonce, encoded_path, encoded_user] = - payload - .split(':') - .collect::<Vec<_>>() - .try_into() - .map_err(|_| invalid())?; + // Parse payload: workspace_id:service_name:timestamp:nonce:username + let [state_workspace_id, state_service, timestamp, _nonce, encoded_user] = payload + .split(':') + .collect::<Vec<_>>() + .try_into() + .map_err(|_| invalid())?; if state_workspace_id != workspace_id || state_service != service_name.as_str() @@ -150,14 +144,7 @@ async fn validate_signed_state( let received_signature = URL_SAFE_NO_PAD .decode(encoded_signature) .map_err(|_| invalid())?; - mac.verify_slice(&received_signature) - .map_err(|_| invalid())?; - - URL_SAFE_NO_PAD - .decode(encoded_path) - .ok() - .and_then(|bytes| String::from_utf8(bytes).ok()) - .ok_or_else(invalid) + mac.verify_slice(&received_signature).map_err(|_| invalid()) } #[cfg(feature = "native_trigger")] @@ -205,87 +192,48 @@ pub struct OAuthConfigResponse { pub redirect_uri: Option<String>, } -/// The OAuth client a connection is made with: the workspace's own when an admin configured one, -/// otherwise the instance's when the instance admin shares it. The flag says which. +/// The OAuth app the workspace configured for the service, if any. Without one, connections use +/// the instance's connect client through the resource connect flow. #[cfg(feature = "native_trigger")] -async fn resolve_oauth_client( +async fn workspace_app( db: &DB, workspace_id: &str, service_name: ServiceName, -) -> Result<(WorkspaceOAuthConfig, bool)> { - let workspace_config = +) -> Result<Option<WorkspaceOAuthConfig>> { + Ok( get_workspace_oauth_config::<WorkspaceOAuthConfig>(db, workspace_id, service_name) .await .ok() - .filter(|c| !c.instance_shared && !c.client_id.is_empty()); - match workspace_config { - Some(config) => Ok((config, false)), - None => Ok((get_instance_oauth_config(db, service_name).await?, true)), - } + .filter(|c| !c.instance_shared && !c.client_id.is_empty()), + ) } -/// Connecting writes the connection's variable and resource at `path`, so a path-scoped token must -/// cover both, whatever the user behind it may write. +#[cfg(feature = "native_trigger")] +async fn require_workspace_app( + db: &DB, + workspace_id: &str, + service_name: ServiceName, +) -> Result<WorkspaceOAuthConfig> { + workspace_app(db, workspace_id, service_name) + .await? + .ok_or_else(|| { + Error::BadRequest(format!( + "This workspace has no {service_name} OAuth app. Connect through the instance's \ + instead." + )) + }) +} + +/// Sharing or disconnecting the connection at `path` acts on its variable and resource, so a +/// path-scoped token must cover both, whatever the user behind it may write. #[cfg(feature = "native_trigger")] fn check_connection_scopes(authed: &ApiAuthed, path: &str) -> Result<()> { check_scopes(authed, || format!("variables:write:{path}"))?; check_scopes(authed, || format!("resources:write:{path}")) } -/// Reconnecting at a path swaps the account every trigger using it acts as, including the shared -/// account's, so only whoever connected it or an admin may replace what is there. Writing the -/// path is not enough: a folder writer would otherwise turn other members' triggers into their own. -/// -/// Admins included, only a connection the trigger connect flow made can be replaced. A resource connected -/// from Resources keeps its scopes and lifecycle there: its token may carry scopes the runnables -/// using it need and that a trigger connect would not ask for. -#[cfg(feature = "native_trigger")] -async fn check_can_replace( - db: &DB, - authed: &ApiAuthed, - workspace_id: &str, - path: &str, -) -> Result<()> { - let existing = sqlx::query!( - r#"SELECT - (SELECT created_by FROM resource WHERE workspace_id = $1 AND path = $2) AS "owner?", - EXISTS(SELECT 1 FROM resource WHERE workspace_id = $1 AND path = $2) - OR EXISTS(SELECT 1 FROM variable WHERE workspace_id = $1 AND path = $2) AS "taken!", - COALESCE((SELECT a.is_workspace_integration FROM variable v - JOIN account a ON a.workspace_id = v.workspace_id AND a.id = v.account - WHERE v.workspace_id = $1 AND v.path = $2), false) AS "managed!""#, - workspace_id, - path, - ) - .fetch_one(db) - .await?; - if existing.taken && !existing.managed { - return Err(Error::BadRequest(format!( - "{path} was not connected by integration triggers. Triggers can use it, but it can only \ - be replaced from Resources. Connect at another path to use a new account." - ))); - } - if authed.is_admin { - return Ok(()); - } - if existing.taken && existing.owner.as_deref() != Some(authed.username.as_str()) { - return Err(Error::NotAuthorized(format!( - "{path} holds a connection someone else created. Connect at another path, or ask an \ - admin to reconnect it." - ))); - } - Ok(()) -} - -#[cfg(feature = "native_trigger")] -fn default_connection_path(authed: &ApiAuthed, service_name: ServiceName) -> String { - format!( - "u/{}/native_{}", - authed.username, - service_name.resource_type() - ) -} - +/// The authorize URL of a resource connect made with the workspace's OAuth app. The token comes +/// back to the caller through `oauth_callback`, which the resource connect saves like any other. #[cfg(feature = "native_trigger")] async fn generate_connect_url( authed: ApiAuthed, @@ -293,107 +241,35 @@ async fn generate_connect_url( Path((workspace_id, service_name)): Path<(String, ServiceName)>, Json(body): Json<ConnectUrlBody>, ) -> JsonResult<String> { - require_native_integration_use(&db, &workspace_id, &authed).await?; - - let (oauth_config, is_instance_shared) = - resolve_oauth_client(&db, &workspace_id, service_name).await?; - - let connection_path = body - .resource_path - .filter(|p| !p.is_empty()) - .unwrap_or_else(|| default_connection_path(&authed, service_name)); - check_connection_scopes(&authed, &connection_path)?; - check_can_replace(&db, &authed, &workspace_id, &connection_path).await?; - - let redirect_uri = redirect_uri_for(&oauth_config, is_instance_shared, service_name); - let scopes = connection_scopes(&db, &workspace_id, &connection_path, service_name).await?; - - // Generate a signed state that is cluster-safe - let state = generate_signed_state( - &db, - &workspace_id, - service_name, - &connection_path, - &authed.username, - ) - .await?; + let oauth_config = require_workspace_app(&db, &workspace_id, service_name).await?; + let redirect_uri = redirect_uri_for(&oauth_config, service_name); + let state = generate_signed_state(&db, &workspace_id, service_name, &authed.username).await?; let auth_url = build_authorization_url( &oauth_config, service_name, &state, &redirect_uri, - &scopes.join(" "), + &body.scopes.join(" "), ); Ok(Json(auth_url)) } -/// Where every connection made with an instance client lands: the resource connect callback each -/// instance client already registers. +/// The redirect URI registered on the workspace app. Providers compare it to the registered one, +/// so the server picks it, identically when authorizing and exchanging. An app saved before it +/// stored its own uses the one the settings showed then. #[cfg(feature = "native_trigger")] -fn canonical_redirect_uri(service_name: ServiceName) -> String { - format!( - "{}/oauth/callback/{}", - &**windmill_common::BASE_URL.load(), - service_name.resource_type() - ) -} - -/// The redirect a workspace app saved before it stored its own: the one the settings showed then. -#[cfg(feature = "native_trigger")] -fn legacy_redirect_uri(service_name: ServiceName) -> String { - format!( - "{}/workspace_settings?tab=native_triggers&service={}", - &**windmill_common::BASE_URL.load(), - service_name.as_str() - ) -} - -/// The redirect URI registered on the client a connection is made with. Providers compare it to -/// the registered one, so the server picks it, identically when authorizing and exchanging. -#[cfg(feature = "native_trigger")] -fn redirect_uri_for( - config: &WorkspaceOAuthConfig, - is_instance_shared: bool, - service_name: ServiceName, -) -> String { - if is_instance_shared { - canonical_redirect_uri(service_name) - } else if config.redirect_uri.is_empty() { - legacy_redirect_uri(service_name) +fn redirect_uri_for(config: &WorkspaceOAuthConfig, service_name: ServiceName) -> String { + if config.redirect_uri.is_empty() { + format!( + "{}/workspace_settings?tab=native_triggers&service={}", + &**windmill_common::BASE_URL.load(), + service_name.as_str() + ) } else { config.redirect_uri.clone() } } -/// The scopes to ask for when connecting at `path`: what the service's triggers need, plus whatever -/// the account there already holds, so reconnecting never takes access away from what uses it. -#[cfg(feature = "native_trigger")] -async fn connection_scopes( - db: &DB, - workspace_id: &str, - path: &str, - service_name: ServiceName, -) -> Result<Vec<String>> { - let existing = sqlx::query_scalar!( - "SELECT a.scopes FROM variable v - JOIN account a ON a.workspace_id = v.workspace_id AND a.id = v.account - WHERE v.workspace_id = $1 AND v.path = $2", - workspace_id, - path, - ) - .fetch_optional(db) - .await? - .flatten() - .unwrap_or_default(); - let mut scopes: Vec<String> = service_name.required_scopes(); - for scope in existing { - if !scopes.contains(&scope) { - scopes.push(scope); - } - } - Ok(scopes) -} - #[cfg(feature = "native_trigger")] #[derive(Debug, Deserialize)] struct BasicOAuthData { @@ -716,7 +592,7 @@ async fn list_integrations( } /// Whether the caller can create triggers for this service: the workspace has an OAuth client, the -/// instance shares one, or the caller can already use a connection, such as a connected resource. +/// instance has one, or the caller can already use a connection, such as a connected resource. #[cfg(feature = "native_trigger")] async fn integration_exist( authed: ApiAuthed, @@ -724,7 +600,7 @@ async fn integration_exist( Extension(user_db): Extension<UserDB>, Path((workspace_id, service_name)): Path<(String, ServiceName)>, ) -> JsonResult<bool> { - if is_instance_sharing_enabled(&db, service_name).await? { + if has_instance_client(&db, service_name).await? { return Ok(Json(true)); } let mut tx = user_db.begin(&authed).await?; @@ -757,8 +633,8 @@ async fn integration_exist( #[cfg(feature = "native_trigger")] #[derive(Debug, Deserialize)] struct ConnectUrlBody { - /// Where to save the connection; defaults to `u/<caller>/native_<resource type>`. - resource_path: Option<String>, + #[serde(default)] + scopes: Vec<String>, } #[cfg(feature = "native_trigger")] @@ -774,17 +650,18 @@ struct NextcloudUserData { id: String, } +#[cfg(feature = "native_trigger")] +/// Exchange the code of a connect made with the workspace's OAuth app, and hand the token back in +/// the shape the resource connect callback answers. The caller saves it like any connected +/// resource, flagged as issued by the workspace app so refreshes use it. #[cfg(feature = "native_trigger")] async fn oauth_callback( authed: ApiAuthed, Extension(db): Extension<DB>, - Extension(user_db): Extension<UserDB>, Path((workspace_id, service_name)): Path<(String, ServiceName)>, Json(body): Json<OAuthCallbackBody>, -) -> JsonResult<String> { - require_native_integration_use(&db, &workspace_id, &authed).await?; - - let resource_path = validate_signed_state( +) -> JsonResult<windmill_oauth::ConnectCallbackResponse> { + validate_signed_state( &db, &body.state, &workspace_id, @@ -792,151 +669,29 @@ async fn oauth_callback( &authed.username, ) .await?; - check_connection_scopes(&authed, &resource_path)?; - check_can_replace(&db, &authed, &workspace_id, &resource_path).await?; - let (oauth_config, is_instance_shared) = - resolve_oauth_client(&db, &workspace_id, service_name).await?; - let redirect_uri = redirect_uri_for(&oauth_config, is_instance_shared, service_name); - // Read before the connection there is replaced: it is the account whose scopes carry over. - let scopes = connection_scopes(&db, &workspace_id, &resource_path, service_name).await?; - - let token_response = + let oauth_config = require_workspace_app(&db, &workspace_id, service_name).await?; + let redirect_uri = redirect_uri_for(&oauth_config, service_name); + let token_json = exchange_code_for_token(&oauth_config, service_name, &body.code, &redirect_uri).await?; + let token = windmill_oauth::parse_token_response(token_json, None)?; - let expires_in = token_response.expires_in.unwrap_or(3600); - - // A user transaction, so the variable and resource policies decide whether the caller may - // write a connection at this path. - let mut tx = user_db.begin(&authed).await?; - - // Reconnecting at a path swaps the token and account in place: the resource and variable keep - // their sharing and description, and the triggers using the path keep working. - let replaced_account = sqlx::query_scalar!( - "SELECT account FROM variable WHERE workspace_id = $1 AND path = $2", - workspace_id, - resource_path, - ) - .fetch_optional(&mut *tx) - .await? - .flatten(); - - // 1. Create account record for token refresh - let account_id = sqlx::query_scalar!( - "INSERT INTO account (workspace_id, client, expires_at, refresh_token, is_workspace_integration, scopes) - VALUES ($1, $2, now() + ($3 || ' seconds')::interval, $4, true, $5) - RETURNING id", - workspace_id, - service_name.as_str(), - expires_in.to_string(), - token_response.refresh_token.as_deref().unwrap_or(""), - &scopes, - ) - .fetch_one(&mut *tx) - .await - .map_err(|e| Error::InternalErr(format!("Failed to create account: {}", e)))?; - - // 2. Create variable with encrypted access token - let mc = build_crypt(&db, &workspace_id).await?; - let encrypted_access_token = encrypt(&mc, &token_response.access_token); - - sqlx::query!( - "INSERT INTO variable (workspace_id, path, value, is_secret, description, account, is_oauth) - VALUES ($1, $2, $3, true, $4, $5, true) - ON CONFLICT (workspace_id, path) DO UPDATE - SET value = EXCLUDED.value, account = EXCLUDED.account", - workspace_id, - resource_path, - encrypted_access_token, - format!("OAuth token for {} workspace integration", service_name), - account_id, - ) - .execute(&mut *tx) - .await - .map_err(|e| Error::InternalErr(format!("Failed to create variable: {}", e)))?; - - // 3. Create resource pointing to the variable - let resource_value = if service_name == ServiceName::Nextcloud { - let token_value = format!("$var:{}", resource_path); + let mut resource_fields = HashMap::new(); + if service_name == ServiceName::Nextcloud { let base_url = &oauth_config.base_url; - let user_id = fetch_nextcloud_user_id(base_url, &token_response.access_token).await; - match user_id { - Ok(user_id) => json!({ - "token": token_value, - "baseUrl": base_url, - "userId": user_id, - }), - Err(e) => { - tracing::warn!("Failed to fetch Nextcloud user info: {e}"); - json!({ - "token": token_value, - "baseUrl": base_url, - }) + resource_fields.insert("baseUrl".to_string(), json!(base_url)); + match fetch_nextcloud_user_id(base_url, &token.access_token.to_string()).await { + Ok(user_id) => { + resource_fields.insert("userId".to_string(), json!(user_id)); } + Err(e) => tracing::warn!("Failed to fetch Nextcloud user info: {e}"), } - } else { - json!({ "token": format!("$var:{}", resource_path) }) - }; - - sqlx::query!( - "INSERT INTO resource (workspace_id, path, value, resource_type, description, created_by) - VALUES ($1, $2, $3, $4, $5, $6) - ON CONFLICT (workspace_id, path) DO UPDATE - SET value = EXCLUDED.value, resource_type = EXCLUDED.resource_type", - workspace_id, - resource_path, - resource_value, - service_name.resource_type(), - format!("{} workspace integration", service_name), - authed.username, - ) - .execute(&mut *tx) - .await - .map_err(|e| Error::InternalErr(format!("Failed to create resource: {}", e)))?; - - // 4. A connection made with the instance's client records that in the workspace, with the - // server its token belongs to. Token refresh reads the client from this row, so it must - // exist for every connection. - if is_instance_shared { - sqlx::query!( - "INSERT INTO workspace_integrations (workspace_id, service_name, oauth_data, created_by) - VALUES ($1, $2, $3, $4) - ON CONFLICT (workspace_id, service_name) DO UPDATE SET oauth_data = EXCLUDED.oauth_data - WHERE (workspace_integrations.oauth_data->>'instance_shared')::boolean", - workspace_id, - service_name as ServiceName, - json!({ "instance_shared": true, "base_url": oauth_config.base_url }), - authed.username, - ) - .execute(&mut *tx) - .await?; } - audit_log( - &mut *tx, - &authed, - &format!("workspace_integrations.{}.connect", service_name), - ActionKind::Create, - &workspace_id, - Some(&resource_path), - None, - ) - .await?; - - tx.commit().await?; - delete_unlinked_account(&db, &workspace_id, replaced_account).await; - - Ok(Json(resource_path)) -} - -/// Token response from OAuth token exchange -#[cfg(feature = "native_trigger")] -#[derive(Debug, Deserialize)] -struct TokenResponse { - access_token: String, - refresh_token: Option<String>, - #[serde(default)] - expires_in: Option<u64>, + Ok(Json(windmill_oauth::ConnectCallbackResponse { + token, + resource_fields, + })) } /// Build an OAuth client for native trigger services using windmill-oauth. @@ -977,10 +732,10 @@ async fn exchange_code_for_token( service_name: ServiceName, code: &str, redirect_uri: &str, -) -> Result<TokenResponse> { +) -> Result<serde_json::Value> { let client = build_native_oauth_client(config, service_name, redirect_uri)?; - let token_response: TokenResponse = client + let token_response: serde_json::Value = client .exchange_code(code.to_string()) .with_client(&*OAUTH_HTTP_CLIENT) .execute() @@ -1125,26 +880,8 @@ pub async fn cleanup_connection( Ok(account_id) } -/// Delete a connection's account once no variable links it any more. Any variable can link any -/// account, so another one may still hold it; the check needs `db`, since the caller's own -/// transaction does not see variables it cannot read. #[cfg(feature = "native_trigger")] -pub async fn delete_unlinked_account(db: &DB, workspace_id: &str, account_id: Option<i32>) { - let Some(account_id) = account_id else { - return; - }; - if let Err(e) = sqlx::query!( - "DELETE FROM account WHERE workspace_id = $1 AND id = $2 - AND NOT EXISTS (SELECT 1 FROM variable WHERE workspace_id = $1 AND account = $2)", - workspace_id, - account_id, - ) - .execute(db) - .await - { - tracing::error!("Failed to delete account {account_id} in {workspace_id}: {e}"); - } -} +use windmill_store::variables::delete_unlinked_account; /// Remove every connection of a service in the workspace. #[cfg(feature = "native_trigger")] @@ -1161,28 +898,23 @@ pub async fn cleanup_service_connections( .fetch_all(&mut *tx) .await?; - let paths = sqlx::query_scalar!( - "DELETE FROM variable WHERE workspace_id = $1 AND account = ANY($2) RETURNING path", + // Scripts and flows may use these resources too, so they stay, with a token that no longer + // refreshes, until someone reconnects them. + sqlx::query!( + "UPDATE variable SET account = NULL WHERE workspace_id = $1 AND account = ANY($2)", workspace_id, &account_ids, ) - .fetch_all(&mut *tx) - .await?; - - sqlx::query!( - "DELETE FROM resource WHERE workspace_id = $1 AND path = ANY($2)", - workspace_id, - &paths, - ) .execute(&mut *tx) .await?; Ok(()) } -/// Check if the instance admin has enabled sharing of OAuth credentials for a given service. +/// Whether the instance has a connect client for the service, which every workspace connects +/// through when it has no OAuth app of its own. #[cfg(feature = "native_trigger")] -async fn is_instance_sharing_enabled(db: &DB, service_name: ServiceName) -> Result<bool> { +async fn has_instance_client(db: &DB, service_name: ServiceName) -> Result<bool> { let entry = match instance_oauth_entry(db, service_name).await? { Some(v) => v, None => return Ok(false), @@ -1190,52 +922,11 @@ async fn is_instance_sharing_enabled(db: &DB, service_name: ServiceName) -> Resu let id = entry.get("id").and_then(|v| v.as_str()).unwrap_or(""); let secret = entry.get("secret").and_then(|v| v.as_str()).unwrap_or(""); - let share = entry - .get("share_with_workspaces") - .and_then(|v| v.as_bool()) - .unwrap_or(false); // A Nextcloud client belongs to the one server the instance names. let has_server = service_name != ServiceName::Nextcloud || !instance_base_url(&entry).is_empty(); - Ok(!id.is_empty() && !secret.is_empty() && share && has_server) -} - -/// Read instance-level OAuth credentials for a service (when sharing is enabled). -#[cfg(feature = "native_trigger")] -async fn get_instance_oauth_config( - db: &DB, - service_name: ServiceName, -) -> Result<WorkspaceOAuthConfig> { - if !is_instance_sharing_enabled(db, service_name).await? { - return Err(Error::BadRequest(format!( - "No {service_name} OAuth app is configured for this workspace. A workspace admin can \ - configure one in the workspace settings, under integration triggers." - ))); - } - - let (client_id, client_secret) = - windmill_common::global_settings::get_instance_oauth_credentials( - db, - service_name.resource_type(), - ) - .await?; - // Google and GitHub use absolute URLs. - let base_url = match service_name { - ServiceName::Nextcloud => instance_oauth_entry(db, service_name) - .await? - .map(|e| instance_base_url(&e)) - .unwrap_or_default(), - _ => String::new(), - }; - - Ok(WorkspaceOAuthConfig { - client_id, - client_secret, - base_url, - instance_shared: false, - redirect_uri: String::new(), - }) + Ok(!id.is_empty() && !secret.is_empty() && has_server) } #[cfg(feature = "native_trigger")] @@ -1245,8 +936,43 @@ async fn check_instance_sharing_available( Path((workspace_id, service_name)): Path<(String, ServiceName)>, ) -> JsonResult<bool> { require_admin(authed.is_admin, &workspace_id)?; - let available = is_instance_sharing_enabled(&db, service_name).await?; - Ok(Json(available)) + Ok(Json(has_instance_client(&db, service_name).await?)) +} + +/// The scopes the service's triggers need, which a connection made for them requests. +#[cfg(feature = "native_trigger")] +async fn required_scopes( + _authed: ApiAuthed, + Path((_workspace_id, service_name)): Path<(String, ServiceName)>, +) -> JsonResult<Vec<String>> { + Ok(Json( + service_name + .required_scopes() + .into_iter() + .filter(|s| !s.is_empty()) + .collect(), + )) +} + +/// The services this workspace has its own OAuth app for. Any member may read it: the resource +/// connect uses it to pick the client a connection is made with. +#[cfg(feature = "native_trigger")] +async fn list_workspace_apps( + _authed: ApiAuthed, + Extension(db): Extension<DB>, + Path(workspace_id): Path<String>, +) -> JsonResult<Vec<ServiceName>> { + use strum::IntoEnumIterator; + let mut services = vec![]; + for service_name in ServiceName::iter() { + if workspace_app(&db, &workspace_id, service_name) + .await? + .is_some() + { + services.push(service_name); + } + } + Ok(Json(services)) } #[cfg(feature = "native_trigger")] @@ -1318,22 +1044,14 @@ async fn set_workspace_connection( .execute(&mut *tx) .await? .rows_affected(); - // A workspace whose connections all come from Resources has no row yet; with the instance - // client shared, it gets the same row a trigger connect would have written. + // A workspace without its own OAuth app has no row yet. Its row only holds the shared path. if updated == 0 { - if !is_instance_sharing_enabled(&db, service_name).await? { - return Err(Error::NotFound(format!( - "{service_name} is not set up in this workspace" - ))); - } - let config = get_instance_oauth_config(&db, service_name).await?; sqlx::query!( "INSERT INTO workspace_integrations (workspace_id, service_name, oauth_data, resource_path, created_by) - VALUES ($1, $2, $3, $4, $5)", + VALUES ($1, $2, NULL, $3, $4)", workspace_id, service_name as ServiceName, - json!({ "instance_shared": true, "base_url": config.base_url }), path, authed.username, ) @@ -1383,20 +1101,10 @@ async fn delete_connection( let mut tx = user_db.clone().begin(&authed).await?; let usable = list_usable_connections(&db, &mut tx, &workspace_id, service_name).await?; tx.commit().await?; - match usable.iter().find(|c| c.path == path) { - None => { - return Err(Error::NotFound(format!( - "No {service_name} connection at {path}" - ))) - } - // Disconnecting deletes the resource, which runnables may use: that is for Resources. - Some(c) if !c.managed => { - return Err(Error::BadRequest(format!( - "{path} is a resource connected outside integration triggers. Delete it from \ - Resources instead." - ))) - } - Some(_) => {} + if !usable.iter().any(|c| c.path == path) { + return Err(Error::NotFound(format!( + "No {service_name} connection at {path}" + ))); } // Disconnecting deletes these triggers, so a path-scoped token must cover each of them. Only @@ -1489,6 +1197,8 @@ async fn delete_connection( pub fn workspaced_service() -> Router { let router = Router::new() .route("/list", get(list_integrations)) + .route("/workspace_apps", get(list_workspace_apps)) + .route("/{service_name}/required_scopes", get(required_scopes)) .route("/{service_name}/exists", get(integration_exist)) .route("/{service_name}/create", post(create_workspace_integration)) .route( diff --git a/backend/windmill-queue/src/asset_dispatch.rs b/backend/windmill-queue/src/asset_dispatch.rs index 878ff56069..fd71f83a87 100644 --- a/backend/windmill-queue/src/asset_dispatch.rs +++ b/backend/windmill-queue/src/asset_dispatch.rs @@ -867,7 +867,7 @@ async fn push_subscriber( // the subscriber runs as its own deployer. let args = windmill_common::variables::omit_untrusted_interpolation( args, - "The following resource has been omitted for security reasons: ", + windmill_common::variables::UNRESOLVED_RESOURCE, ); // Attribute the dispatched run to a synthetic user so audit logs reflect diff --git a/backend/windmill-queue/src/failed_only_restart.rs b/backend/windmill-queue/src/failed_only_restart.rs index 67c5573884..5ef82dd6c2 100644 --- a/backend/windmill-queue/src/failed_only_restart.rs +++ b/backend/windmill-queue/src/failed_only_restart.rs @@ -76,14 +76,13 @@ pub(crate) async fn create_failed_only_module( ) .fetch_all(db) .await?; - // An iteration recovered by the error handler completed as a failure but is recorded - // as a success of the step, so it is kept too. - let recorded_success = module.flow_jobs_success().unwrap_or_default(); + // Kept only by the completed status the parallel step judges its own success by: an + // iteration recovered by the error handler is stored as failed, so keeping it would fail + // the restarted step again. let flow_jobs: Vec<Uuid> = original_jobs .iter() - .enumerate() - .map(|(i, job)| { - if succeeded.contains(job) || recorded_success.get(i) == Some(&Some(true)) { + .map(|job| { + if succeeded.contains(job) { *job } else { Uuid::nil() @@ -139,7 +138,12 @@ pub(crate) async fn create_failed_only_module( Ok(FlowStatusModule::InProgress { id: module.id(), job: Uuid::nil(), - iterator: is_loop.then(|| FlowIterator { index: kept, itered, itered_len: Some(n) }), + iterator: is_loop.then(|| FlowIterator { + index: kept, + itered, + itered_len: Some(n), + failure_threshold: None, + }), flow_jobs_success: Some( flow_jobs .iter() diff --git a/backend/windmill-queue/src/jobs.rs b/backend/windmill-queue/src/jobs.rs index e3d488bbea..404988d811 100644 --- a/backend/windmill-queue/src/jobs.rs +++ b/backend/windmill-queue/src/jobs.rs @@ -771,7 +771,8 @@ where /// Carries the authority of the deploy, which every caller has authorized: it cancels and pushes /// runs at `script_path` without an `Authed` of its own. A replacement runs as the deployed /// version's identity when it names one and otherwise as the identity of the run it replaces, and -/// a run only moves to a tag that identity may use. +/// a run only moves to a tag that identity may use. A run that has its identity from its own +/// version's `on_behalf_of` only moves when the deploy names one too or comes from that identity. /// /// Errors are logged, never returned: a deploy stands whatever happens to the runs of its earlier /// versions. @@ -856,7 +857,7 @@ async fn restart_perpetual_runs_at_path( "SELECT q.id AS \"id!\", j.created_by, j.permissioned_as, j.permissioned_as_email, \ j.trigger, j.trigger_kind AS \"trigger_kind: TriggerKindLabel\", j.preprocessed, \ j.args AS \"args: sqlx::types::Json<HashMap<String, Box<RawValue>>>\", \ - p.job_token_scopes AS \"job_token_scopes?\" \ + p.job_token_scopes AS \"job_token_scopes?\", s.on_behalf_of AS version_on_behalf_of \ FROM v2_job_queue q JOIN v2_job j USING (id) \ JOIN script s ON s.workspace_id = j.workspace_id AND s.hash = j.runnable_id \ LEFT JOIN job_perms p ON p.job_id = q.id \ @@ -925,6 +926,8 @@ struct PerpetualRunToRestart { args: Option<sqlx::types::Json<HashMap<String, Box<RawValue>>>>, /// Its effective token scopes: the replacement never holds a wider token. job_token_scopes: Option<Vec<String>>, + /// The identity its own version runs as, if that version names one. + version_on_behalf_of: Option<String>, } /// What every run at the path moves to. @@ -947,10 +950,36 @@ async fn restart_perpetual_run( let RestartOnVersion { payload, tag, timeout, dedicated_worker, on_behalf_of } = version; let (email, permissioned_as) = match on_behalf_of { Some(obo) => (obo.email.clone(), obo.permissioned_as.clone()), - None => ( - run.permissioned_as_email.clone(), - run.permissioned_as.clone(), - ), + None => { + // That identity belongs to the code of the run's own version: another deployer's + // code must not inherit it. + if let Some(obo) = run.version_on_behalf_of.as_deref().filter(|obo| { + *obo != windmill_common::users::username_to_permissioned_as(deployed_by) + }) { + tracing::warn!( + "Perpetual run {} stays on its version: it runs as its version's \ + on_behalf_of and the deployed version of {script_path} names none", + run.id + ); + append_logs( + &run.id, + w_id, + format!( + "\nThis perpetual run keeps its current version: that version runs as \ + {obo}, and the version deployed by {deployed_by} sets no run on behalf \ + of. Redeploy with run on behalf of {obo}, have {obo} deploy it, or \ + cancel and restart the run.\n" + ), + &Connection::from(db.clone()), + ) + .await; + return Ok(()); + } + ( + run.permissioned_as_email.clone(), + run.permissioned_as.clone(), + ) + } }; let args = run.args.clone().map(|args| args.0).unwrap_or_default(); // The run's own tag was checked when the loop started; the deployed version's has not @@ -3720,7 +3749,7 @@ pub(crate) async fn push_variable_expiration_handler<'c>( // `$res:` references, which is how the handler gets its token. let mut extra = omit_untrusted_interpolation( serde_json::from_value(serde_json::to_value(expiring)?)?, - "The following resource has been omitted for security reasons: ", + windmill_common::variables::UNRESOLVED_RESOURCE, ); if let Some(args_v) = extra_args { @@ -3881,10 +3910,7 @@ fn sanitize_result<T: Serialize + Send + Sync>(result: Json<&T>) -> HashMap<Stri let as_str = serde_json::to_string(result.0).unwrap_or_else(|_| "{}".to_string()); let args = serde_json::from_str::<HashMap<String, Box<RawValue>>>(&as_str) .unwrap_or_else(|_| [("error".to_string(), RawValue::from_string(as_str).unwrap())].into()); - omit_untrusted_interpolation( - args, - "The following resource has been omitted for security reasons: ", - ) + omit_untrusted_interpolation(args, windmill_common::variables::UNRESOLVED_RESOURCE) } // #[derive(Serialize)] @@ -5619,6 +5645,40 @@ pub async fn custom_concurrency_key( .await } +/// A job's concurrency key, and whether its limit has held it back without letting it in yet. +pub async fn concurrency_key_and_hold( + db: &Pool<Postgres>, + job_id: &Uuid, +) -> windmill_common::error::Result<Option<(String, bool)>> { + let fut = async || { + sqlx::query!( + "SELECT key, original_scheduled_for IS NOT NULL AND released_at IS NULL AS \"held!\" + FROM concurrency_key WHERE job_id = $1", + job_id + ) + .fetch_optional(db) + .await + }; + fut.retry( + ConstantBuilder::default() + .with_delay(std::time::Duration::from_secs(3)) + .with_max_times(5) + .build(), + ) + .notify(|err, dur| { + tracing::error!( + "Could not get concurrency key for job {job_id}, retrying in {dur:#?}, err: {err:#?}" + ); + }) + .await + .map(|r| r.map(|r| (r.key, r.held))) + .map_err(|e| { + Error::internal_err(format!( + "Could not get concurrency key for job {job_id}: {e:#}" + )) + }) +} + pub async fn concurrency_key( db: &Pool<Postgres>, id: &Uuid, @@ -6564,10 +6624,7 @@ impl PushArgsOwned { /// some trigger pushes carry args their author wrote, whose references must resolve. pub fn omit_untrusted_interpolation(self) -> Self { let omit = |args| { - omit_untrusted_interpolation( - args, - "The following resource has been omitted for security reasons: ", - ) + omit_untrusted_interpolation(args, windmill_common::variables::UNRESOLVED_RESOURCE) }; PushArgsOwned { args: omit(self.args), extra: self.extra.map(omit) } } @@ -6770,10 +6827,14 @@ async fn fetch_pushed_flow_version( if lite { match cache::flow::fetch_version_lite($e, version).await { Ok(data) => Ok(data), - Err(_) => cache::flow::fetch_version($e, version).await, + Err(_) => cache::flow::fetch_version($e, version) + .await + .and_then(cache::flow::as_run_version), } } else { - cache::flow::fetch_version($e, version).await + cache::flow::fetch_version($e, version) + .await + .and_then(cache::flow::as_run_version) } }; } @@ -8979,6 +9040,7 @@ fn create_restarted_module( index: branch_or_iteration_n - 1, itered: None, itered_len: None, + failure_threshold: None, }), flow_jobs: Some(new_flow_jobs), flow_jobs_success: new_flow_jobs_success, @@ -9099,7 +9161,9 @@ pub async fn fetch_restart_flow_version( "flow version {version} is not a version of flow {flow_path} in workspace {workspace_id}" ))); } - cache::flow::fetch_version(db, version).await + cache::flow::fetch_version(db, version) + .await + .and_then(cache::flow::as_run_version) } // A restart copies the steps before the restart step as completed, and the worker only gates the diff --git a/backend/windmill-store/src/oauth_refresh_oss.rs b/backend/windmill-store/src/oauth_refresh_oss.rs index a0d0926510..57f6083ff5 100644 --- a/backend/windmill-store/src/oauth_refresh_oss.rs +++ b/backend/windmill-store/src/oauth_refresh_oss.rs @@ -152,13 +152,19 @@ where if !paths.iter().any(|p| p == path) { paths.push(path.to_string()); } + // A variable a reconnect moved to another account is skipped; the account's other variables + // and its rotated refresh token are still saved. + let mut moved = false; let mut stored = Ok(()); for p in &paths { - stored = - crate::secret_backend_ext::store_oauth_token_value(db, w_id, p, &token.access_token) - .await; - if stored.is_err() { - break; + match crate::secret_backend_ext::store_oauth_token_value(db, w_id, p, id, &token.access_token) + .await + { + Ok(written) => moved |= !written && p == path, + Err(e) => { + stored = Err(e); + break; + } } } sqlx::query!( @@ -177,6 +183,9 @@ where .await?; stored?; + if moved { + return current_token(db, w_id, path).await; + } Ok(token.access_token) } diff --git a/backend/windmill-store/src/oauth_refresh_secret_backend_tests.rs b/backend/windmill-store/src/oauth_refresh_secret_backend_tests.rs index 5a11dea03e..62c71062a2 100644 --- a/backend/windmill-store/src/oauth_refresh_secret_backend_tests.rs +++ b/backend/windmill-store/src/oauth_refresh_secret_backend_tests.rs @@ -210,7 +210,7 @@ async fn database_backend_persists_refreshed_token() { set_backend(&db, serde_json::json!({ "type": "Database" })).await; setup_workspace(&db, w_id).await; - let _ = simulate_connect(&db, w_id, path, "OLD_TOKEN").await; + let account_id = simulate_connect(&db, w_id, path, "OLD_TOKEN").await; // Connect-time token is served. let v = variable_value(&db, w_id, path).await; @@ -220,7 +220,7 @@ async fn database_backend_persists_refreshed_token() { ); // Refresh persists the new token. - store_oauth_token_value(&db, w_id, path, "NEW_TOKEN") + store_oauth_token_value(&db, w_id, path, account_id, "NEW_TOKEN") .await .unwrap(); @@ -250,7 +250,7 @@ async fn external_backend_persists_refreshed_token() { set_backend(&db, aws_sm_config(&aws_sm_endpoint())).await; setup_workspace(&db, w_id).await; - let _ = simulate_connect(&db, w_id, path, "OLD_TOKEN").await; + let account_id = simulate_connect(&db, w_id, path, "OLD_TOKEN").await; // Connect-time token is served from the external store. let marker = variable_value(&db, w_id, path).await; @@ -282,7 +282,7 @@ async fn external_backend_persists_refreshed_token() { ); // The fix: persist through the backend. - store_oauth_token_value(&db, w_id, path, "NEW_TOKEN") + store_oauth_token_value(&db, w_id, path, account_id, "NEW_TOKEN") .await .unwrap(); @@ -326,7 +326,7 @@ async fn failed_persist_resets_account_expiry() { // Point the backend at an unreachable endpoint so the persist fails. set_backend(&db, aws_sm_config("http://127.0.0.1:1")).await; - let res = store_oauth_token_value(&db, w_id, path, "NEW_TOKEN").await; + let res = store_oauth_token_value(&db, w_id, path, account_id, "NEW_TOKEN").await; assert!(res.is_err(), "persist to unreachable backend should fail"); assert!( account_expires_in_past(&db, w_id, account_id).await, diff --git a/backend/windmill-store/src/resources.rs b/backend/windmill-store/src/resources.rs index 85600006ce..6ea5d5bbe3 100644 --- a/backend/windmill-store/src/resources.rs +++ b/backend/windmill-store/src/resources.rs @@ -25,7 +25,7 @@ use windmill_common::workspaces::{check_deploy_rules, operator_can_draft, RuleCh use crate::secret_backend_ext::rename_vault_secret; use crate::var_resource_cache::{auth_identity, cache_resource, get_cached_resource}; -use crate::variables::{describe_authed, describe_extra_perms}; +use crate::variables::{access_denied_message, folder_perms_of}; use windmill_common::utils::{ check_proper_path, check_proper_type_name, escape_ilike_pattern, sanitize_db_error, BulkDeleteRequest, @@ -194,6 +194,14 @@ pub struct ListableResource { /// The OAuth scopes the linked account was connected with. #[serde(skip_serializing_if = "Option::is_none")] pub scopes: Option<Vec<String>>, + /// The OAuth client the linked account refreshes through, which a reconnect goes through + /// again (a `_sandbox` client included). + #[serde(skip_serializing_if = "Option::is_none")] + pub client: Option<String>, + /// The linked account came through the workspace's own OAuth app, which a reconnect uses + /// again. + #[serde(skip_serializing_if = "Option::is_none")] + pub is_workspace_integration: Option<bool>, #[serde(skip_serializing_if = "Option::is_none")] pub labels: Option<Vec<String>>, /// Labels inherited from the parent folder, computed at read time. @@ -379,6 +387,8 @@ async fn list_resources( "account.refresh_error", "account.grant_type", "account.scopes", + "account.client", + "account.is_workspace_integration", "resource.created_by", "resource.edited_at", "resource.labels", @@ -582,6 +592,8 @@ async fn list_resources( refresh_error: None, account: None, scopes: None, + client: None, + is_workspace_integration: None, labels, // No deployed row to inherit folder labels from. inherited_labels: None, @@ -616,7 +628,8 @@ async fn get_resource( resource.labels, folder_labels(resource.workspace_id, resource.path) as \"inherited_labels?\", (now() > account.expires_at) as is_expired, account.refresh_token != '' as is_refreshed, - account.refresh_error, account.scopes as \"scopes?\", + account.refresh_error, account.scopes as \"scopes?\", account.client as \"client?\", + account.is_workspace_integration as \"is_workspace_integration?\", variable.path IS NOT NULL as is_linked, variable.is_oauth as \"is_oauth?\", variable.account, @@ -724,33 +737,14 @@ pub async fn explain_resource_perm_error( .fetch_optional(db) .await? .ok_or_else(|| Error::NotFound(format!("Resource {} not found", path)))?; - if path.starts_with("f/") { - let folder = path.split("/").nth(1).ok_or_else(|| { - Error::BadRequest(format!( - "path {} should have at least 2 components separated by /", - path - )) - })?; - let folder_extra_perms = sqlx::query_scalar!( - "SELECT extra_perms from folder WHERE name = $1 AND workspace_id = $2", - folder, - w_id - ) - .fetch_optional(db) - .await?; - return Err(Error::NotAuthorized(format!( - "Resource exists but you don't have access to it:\nresource perms: {}\nfolder perms: {}\nauthed as: {}", - describe_extra_perms(Some(&extra_perms)), - describe_extra_perms(folder_extra_perms.as_ref()), - describe_authed(Some(authed)) - ))); - } else { - return Err(Error::NotAuthorized(format!( - "Resource exists but you don't have access to it:\nresource perms: {}\nauthed as: {}", - describe_extra_perms(Some(&extra_perms)), - describe_authed(Some(authed)) - ))); - } + let folder_perms = folder_perms_of(path, w_id, db).await?; + Err(Error::NotAuthorized(access_denied_message( + "resource", + path, + &extra_perms, + folder_perms.as_ref().map(Option::as_ref), + Some(authed), + ))) } async fn custom_component( @@ -790,6 +784,11 @@ async fn get_resource_value_interpolated( let path = path.to_path(); check_scopes(&authed, || format!("resources:read:{}", path))?; + if let Some(dbname) = path.strip_prefix("CUSTOM_INSTANCE_DB/") { + return custom_instance_db_value(&authed, &db, dbname) + .await + .map(|v| Json(Some(v))); + } let db_with_opt_authed = DbWithOptAuthed::from_authed(&authed, db.clone(), Some(user_db.clone())); get_resource_value_interpolated_internal( @@ -804,6 +803,47 @@ async fn get_resource_value_interpolated( .map(|success| Json(success)) } +/// The instance database's own credentials for `CUSTOM_INSTANCE_DB/<dbname>`. Only reachable from +/// a route where the caller names that path in their own request: a lookup made on someone's +/// behalf (an app's inputs resolved as its viewer, a resource value's references) must never +/// reach it, so `get_resource_value_interpolated_internal` does not serve it. +pub async fn custom_instance_db_value( + authed: &ApiAuthed, + db: &DB, + dbname: &str, +) -> Result<serde_json::Value> { + // A job's WM_TOKEN must never reach this superadmin-only path even if it runs on behalf of a + // superadmin. Read the job provenance from the *authenticated* identity, never a + // caller-supplied `job_id` param. + if authed.job_id.is_some() { + return Err(Error::NotAuthorized( + "CUSTOM_INSTANCE_DB cannot be resolved from a job token ($WM_TOKEN)".to_string(), + )); + } + if authed.super_admin_withheld { + return Err(Error::NotAuthorized( + "CUSTOM_INSTANCE_DB requires a token carrying superadmin rights".to_string(), + )); + } + require_super_admin_email(db, &authed.email).await?; + let mut pg_creds = PgDatabase::parse_uri(&get_database_url().await?.as_str().await)?; + pg_creds.dbname = dbname.to_string(); + serde_json::to_value(&pg_creds) + .map_err(|e| Error::internal_err(format!("Error serializing pg creds: {}", e))) +} + +/// Refuses `CUSTOM_INSTANCE_DB/<db>` on a lookup that is not the caller's own request for it. +fn refuse_custom_instance_db(path: &str) -> Result<()> { + match path.strip_prefix("CUSTOM_INSTANCE_DB/") { + Some(dbname) => Err(Error::BadRequest(format!( + "CUSTOM_INSTANCE_DB/{dbname} is resolved only when a superadmin requests it directly. \ + It cannot be an app input or be referenced from another resource; create a \ + postgresql resource with those credentials instead." + ))), + None => Ok(()), + } +} + pub async fn get_resource_value_interpolated_internal<'a>( db_with_opt_authed: &'a DbWithOptAuthed<'a, ApiAuthed>, workspace: &str, @@ -812,25 +852,7 @@ pub async fn get_resource_value_interpolated_internal<'a>( token_for_context: Option<&str>, allow_cache: bool, ) -> Result<Option<serde_json::Value>> { - // This is a special syntax to help debugging custom instance databases - if let Some(dbname) = path.strip_prefix("CUSTOM_INSTANCE_DB/") { - // A job's WM_TOKEN must never reach this superadmin-only path even if it - // runs on behalf of a superadmin (GHSA-hfh4-cx4h-3fcr). Read the job - // provenance from the *authenticated* identity, never the caller-supplied - // `job_id` param (which comes from an untrusted query string). - if db_with_opt_authed.authed().and_then(|a| a.job_id).is_some() { - return Err(Error::NotAuthorized( - "CUSTOM_INSTANCE_DB cannot be resolved from a job token ($WM_TOKEN)".to_string(), - )); - } - require_super_admin_email(db_with_opt_authed.db(), &db_with_opt_authed.email()).await?; - let mut pg_creds = PgDatabase::parse_uri(&get_database_url().await?.as_str().await)?; - pg_creds.dbname = dbname.to_string(); - let pg_creds = serde_json::to_value(&pg_creds) - .map_err(|e| Error::internal_err(format!("Error serializing pg creds: {}", e)))?; - return Ok(Some(pg_creds)); - } - + refuse_custom_instance_db(path)?; // Scope the cache to the caller's full authorization identity (not just email): the // cached value is already decrypted/interpolated under this caller's RLS context, so it // must never be served to a context that resolves to different permissions. Only @@ -1032,6 +1054,7 @@ pub async fn transform_json_value_tracked( "Invalid resource path: {path}" ))); } + refuse_custom_instance_db(path)?; check_interpolation_scope(db_with_opt_authed, "resources", path, None)?; let mut tx: Transaction<'_, Postgres> = db_with_opt_authed.begin().await?; let v = sqlx::query_scalar!( @@ -2223,6 +2246,10 @@ async fn update_resource( .await?; if let Some(var) = linked_var { + // The variable moves with the resource, so a scoped token needs write access to it + // at both paths. + check_scopes(&authed, || format!("variables:write:{}", path))?; + check_scopes(&authed, || format!("variables:write:{}", npath))?; if var.is_secret { // Check if this is a Vault-stored secret and rename it if let Some(new_value) = @@ -2593,17 +2620,21 @@ async fn resolve_agent_on_behalf_of( } /// Held until the write commits: whether a value is resolved as an agent's depends on the type -/// read after this, and a concurrent retype into an agent must not land between the two. +/// read after this, and a concurrent retype into an agent must not land between the two. A +/// missing row is refused rather than passed over: nothing would be locked, and a resource +/// created meanwhile would take a write judged against no type at all. async fn lock_resource_row( tx: &mut Transaction<'_, Postgres>, w_id: &str, path: &str, ) -> Result<()> { - sqlx::query("SELECT 1 FROM resource WHERE workspace_id = $1 AND path = $2 FOR UPDATE") - .bind(w_id) - .bind(path) - .execute(&mut **tx) - .await?; + let locked = + sqlx::query("SELECT 1 FROM resource WHERE workspace_id = $1 AND path = $2 FOR UPDATE") + .bind(w_id) + .bind(path) + .fetch_optional(&mut **tx) + .await?; + not_found_if_none(locked, "Resource", path)?; Ok(()) } @@ -3509,6 +3540,8 @@ async fn create_resource_type( Path(w_id): Path<String>, Json(resource_type): Json<CreateResourceType>, ) -> Result<(StatusCode, String)> { + // Resource types are shared by the whole workspace, so a path-scoped token cannot write them. + check_scopes(&authed, || "resources:write".to_string())?; if let RuleCheckResult::Blocked(msg) = check_deploy_rules( &w_id, AuditAuthorable::username(&authed), @@ -3620,6 +3653,7 @@ async fn delete_resource_type( Path((w_id, name)): Path<(String, String)>, ) -> Result<String> { require_admin(authed.is_admin, &authed.username)?; + check_scopes(&authed, || "resources:write".to_string())?; if let RuleCheckResult::Blocked(msg) = check_deploy_rules( &w_id, AuditAuthorable::username(&authed), @@ -3684,6 +3718,7 @@ async fn update_resource_type( Path((w_id, name)): Path<(String, String)>, Json(ns): Json<EditResourceType>, ) -> Result<String> { + check_scopes(&authed, || "resources:write".to_string())?; use sql_builder::prelude::*; if let RuleCheckResult::Blocked(msg) = check_deploy_rules( &w_id, diff --git a/backend/windmill-store/src/secret_backend_ext.rs b/backend/windmill-store/src/secret_backend_ext.rs index af0380a5ab..40e0770b9e 100644 --- a/backend/windmill-store/src/secret_backend_ext.rs +++ b/backend/windmill-store/src/secret_backend_ext.rs @@ -119,8 +119,8 @@ pub async fn store_managed_secret_value( /// external backend — the account must not end up marked fresh while the served /// secret is stale, or the on-fetch refresh gate (`now() > expires_at`) would keep /// serving the stale token for the whole token lifetime. So on failure we reset -/// `expires_at` to the past and record `refresh_error` — looking the account up via -/// `variable.account` — and the very next fetch retries the refresh. This also +/// `expires_at` to the past and record `refresh_error`, and the very next fetch retries the +/// refresh. This also /// covers another refresher of the account having marked it fresh meanwhile. /// /// Authorization contract: this performs NO access control. It writes the @@ -130,63 +130,69 @@ pub async fn store_managed_secret_value( /// read path has resolved and gated the variable). It is therefore kept /// `pub(crate)` and intended solely for the in-crate refresh adapters. #[cfg(feature = "oauth2")] +/// +/// Returns false, storing nothing, when the variable no longer refreshes through `account_id`: +/// a reconnect moved it to another account while this token was being fetched, and writing it +/// would put the previous identity back. The row lock orders this against that reconnect. pub(crate) async fn store_oauth_token_value( db: &DB, workspace_id: &str, path: &str, + account_id: i32, token: &str, -) -> Result<()> { +) -> Result<bool> { let persist = async { + let mut tx = db.begin().await?; + let linked = sqlx::query_scalar::<_, i32>( + "SELECT 1 FROM variable WHERE workspace_id = $1 AND path = $2 AND account = $3 \ + FOR UPDATE", + ) + .bind(workspace_id) + .bind(path) + .bind(account_id) + .fetch_optional(&mut *tx) + .await? + .is_some(); + if !linked { + return Ok::<bool, Error>(false); + } let value = store_managed_secret_value(db, workspace_id, path, token).await?; sqlx::query("UPDATE variable SET value = $1 WHERE workspace_id = $2 AND path = $3") .bind(value) .bind(workspace_id) .bind(path) - .execute(db) + .execute(&mut *tx) .await?; - Ok::<(), Error>(()) + tx.commit().await?; + Ok(true) } .await; - if let Err(e) = persist { - // Mark the account expired again so the next fetch re-runs the refresh - // instead of serving the now-stale token until it naturally expires. The - // account id is the one linked from the variable being refreshed. - let account_id: Option<i32> = sqlx::query_scalar::<_, Option<i32>>( - "SELECT account FROM variable WHERE workspace_id = $1 AND path = $2", - ) - .bind(workspace_id) - .bind(path) - .fetch_optional(db) - .await - .ok() - .flatten() - .flatten(); - - if let Some(account_id) = account_id { - if let Err(reset_err) = sqlx::query( - "UPDATE account SET expires_at = now() - interval '1 minute', refresh_error = $1 \ - WHERE workspace_id = $2 AND id = $3", - ) - .bind(format!( - "OAuth token was refreshed but persisting it to the secret backend failed: {e}" - )) - .bind(workspace_id) - .bind(account_id) - .execute(db) - .await - { - tracing::error!( - workspace_id = %workspace_id, - account_id = %account_id, - "failed to reset account expiry after token persistence error: {reset_err}" - ); - } - } - return Err(e); + let e = match persist { + Ok(written) => return Ok(written), + Err(e) => e, + }; + // Mark the account expired again so the next fetch re-runs the refresh instead of serving + // the now-stale token until it naturally expires. + if let Err(reset_err) = sqlx::query( + "UPDATE account SET expires_at = now() - interval '1 minute', refresh_error = $1 \ + WHERE workspace_id = $2 AND id = $3", + ) + .bind(format!( + "OAuth token was refreshed but persisting it to the secret backend failed: {e}" + )) + .bind(workspace_id) + .bind(account_id) + .execute(db) + .await + { + tracing::error!( + workspace_id = %workspace_id, + account_id = %account_id, + "failed to reset account expiry after token persistence error: {reset_err}" + ); } - - Ok(()) + Err(e) } /// Delete a secret from the configured backend (if using Vault) @@ -398,3 +404,69 @@ pub async fn rename_vault_secrets_with_prefix( Ok(updates) } + +#[cfg(all(test, feature = "oauth2"))] +mod tests { + use super::*; + + /// A refresh that fetched its token before a reconnect moved the variable to another account + /// must not write that token over the reconnected one, even while the reconnect is still + /// uncommitted when the refresh comes to store. + #[sqlx::test(migrations = "../migrations")] + async fn refresh_does_not_overwrite_a_reconnect(db: DB) { + let w = "w"; + let path = "u/test/conn"; + sqlx::query( + "INSERT INTO workspace (id, name, owner) VALUES ('w', 'w', 'test@windmill.dev')", + ) + .execute(&db) + .await + .unwrap(); + let account = |client: &'static str| { + let db = db.clone(); + async move { + sqlx::query_scalar::<_, i32>( + "INSERT INTO account (workspace_id, client, expires_at, refresh_token) + VALUES ('w', $1, now(), 'r') RETURNING id", + ) + .bind(client) + .fetch_one(&db) + .await + .unwrap() + } + }; + let (old, new) = (account("old").await, account("new").await); + sqlx::query( + "INSERT INTO variable (workspace_id, path, value, is_secret, description, account, is_oauth) + VALUES ('w', $1, 'reconnected', true, '', $2, true)", + ) + .bind(path) + .bind(old) + .execute(&db) + .await + .unwrap(); + + let mut reconnect = db.begin().await.unwrap(); + sqlx::query("UPDATE variable SET account = $1 WHERE workspace_id = 'w' AND path = $2") + .bind(new) + .bind(path) + .execute(&mut *reconnect) + .await + .unwrap(); + let refresh = tokio::spawn({ + let db = db.clone(); + async move { store_oauth_token_value(&db, w, path, old, "stale").await } + }); + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + reconnect.commit().await.unwrap(); + + assert!(!refresh.await.unwrap().unwrap()); + let value: String = + sqlx::query_scalar("SELECT value FROM variable WHERE workspace_id = 'w' AND path = $1") + .bind(path) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(value, "reconnected"); + } +} diff --git a/backend/windmill-store/src/variables.rs b/backend/windmill-store/src/variables.rs index 2e5c4902ba..73c81361ec 100644 --- a/backend/windmill-store/src/variables.rs +++ b/backend/windmill-store/src/variables.rs @@ -85,9 +85,13 @@ pub fn workspaced_service() -> Router { async fn list_contextual_variables( Path(w_id): Path<String>, - ApiAuthed { username, email, .. }: ApiAuthed, + authed: ApiAuthed, Extension(db): Extension<DB>, ) -> JsonResult<Vec<ContextualVariable>> { + // The list carries the workspace's environment variables with their values, which + // belong to no single path. + check_scopes(&authed, || "variables:read".to_string())?; + let ApiAuthed { username, email, .. } = authed; Ok(Json( get_reserved_variables( &db.into(), @@ -480,27 +484,46 @@ async fn get_value( /// The grants alone can't explain a denial: a job started on behalf of another /// user is authorized as that user, so the error has to name who was actually /// asking or it reads as a grant bug. -pub(crate) fn describe_authed(authed: Option<&(impl Authable + Sync)>) -> String { - match authed { - Some(authed) => format!( - "username: {}, email: {}, groups: {:?}, folders: {:?}", - authed.username(), - authed.email(), - authed.groups(), - authed.folders() - ), - None => "unauthenticated".to_string(), - } +fn describe_authed(authed: Option<&(impl Authable + Sync)>) -> String { + let Some(authed) = authed else { + return "You are not signed in.".to_string(); + }; + let groups = if authed.groups().is_empty() { + "none".to_string() + } else { + authed.groups().join(", ") + }; + let folders = if authed.folders().is_empty() { + "none".to_string() + } else { + authed + .folders() + .iter() + .map(|(name, write, owner)| { + let level = if *owner { + "owner" + } else if *write { + "read & write" + } else { + "read only" + }; + format!("f/{name} ({level})") + }) + .collect::<Vec<_>>() + .join(", ") + }; + format!( + "You are acting as {} ({}).\n- your groups: {groups}\n- your folders: {folders}", + authed.username(), + authed.email(), + ) } /// `extra_perms` maps a `u/<user>` or `g/<group>` to whether it may write; the raw `true` / /// `false` reads as allowed / denied, so name the access level instead. -pub(crate) fn describe_extra_perms(perms: Option<&Value>) -> String { - let Some(perms) = perms else { - return "folder not found".to_string(); - }; +fn describe_extra_perms(perms: &Value) -> String { let Some(map) = perms.as_object().filter(|m| !m.is_empty()) else { - return "none".to_string(); + return "nobody".to_string(); }; map.iter() .map(|(grantee, can_write)| match can_write.as_bool() { @@ -512,6 +535,51 @@ pub(crate) fn describe_extra_perms(perms: Option<&Value>) -> String { .join(", ") } +/// Why the caller cannot read an item that exists: who holds access to it, who the caller +/// acted as, and whom to ask. `kind` is `resource` or `variable`; `folder_perms` is read only +/// for an `f/` path, `None` inside it when the folder does not exist. +pub(crate) fn access_denied_message( + kind: &str, + path: &str, + item_perms: &Value, + folder_perms: Option<Option<&Value>>, + authed: Option<&(impl Authable + Sync)>, +) -> String { + let mut parts = path.splitn(3, '/'); + let (space, name) = ( + parts.next().unwrap_or_default(), + parts.next().unwrap_or_default(), + ); + let mut who = format!( + "- shared on the {kind}: {}", + describe_extra_perms(item_perms) + ); + let ask = if space == "f" { + match folder_perms.flatten() { + Some(perms) => { + who.push_str(&format!( + "\n- on folder f/{name}: {}", + describe_extra_perms(perms) + )); + format!("an owner of folder f/{name} or a workspace admin") + } + None => { + who.push_str(&format!("\n- folder f/{name} does not exist")); + "a workspace admin".to_string() + } + } + } else { + who.push_str(&format!("\n- its owner: u/{name}")); + format!("u/{name} or a workspace admin") + }; + format!( + "you cannot read the {kind} {path}. It exists, but nothing grants you access to it.\n\n\ + Who has access:\n{who}\n\n{}\n\n\ + To get access, ask {ask} to share it with you or with a group you are in.", + describe_authed(authed) + ) +} + /// Including the variable's and its folder's `extra_perms` in the error is intended, not a /// leak: who holds access to an item is not secret within a workspace, and it tells the /// denied caller whom to ask. Keep the maps in the message. @@ -529,33 +597,36 @@ async fn explain_variable_perm_error( .fetch_optional(db) .await? .ok_or_else(|| Error::NotFound(format!("Variable {} not found", path)))?; - if path.starts_with("f/") { - let folder = path.split("/").nth(1).ok_or_else(|| { - Error::BadRequest(format!( - "path {} should have at least 2 components separated by /", - path - )) - })?; - let folder_extra_perms = sqlx::query_scalar!( + let folder_perms = folder_perms_of(path, w_id, db).await?; + Err(Error::NotAuthorized(access_denied_message( + "variable", + path, + &extra_perms, + folder_perms.as_ref().map(Option::as_ref), + authed, + ))) +} + +/// For an `f/` path, its folder's `extra_perms` (`None` inside when the folder is gone); +/// `None` for any other path. +pub(crate) async fn folder_perms_of( + path: &str, + w_id: &str, + db: &sqlx::Pool<Postgres>, +) -> windmill_common::error::Result<Option<Option<Value>>> { + let Some(rest) = path.strip_prefix("f/") else { + return Ok(None); + }; + let folder = rest.split('/').next().unwrap_or_default(); + Ok(Some( + sqlx::query_scalar!( "SELECT extra_perms from folder WHERE name = $1 AND workspace_id = $2", folder, w_id ) .fetch_optional(db) - .await?; - return Err(Error::NotAuthorized(format!( - "Variable exists but you don't have access to it:\nvariable perms: {}\nfolder perms: {}\nauthed as: {}", - describe_extra_perms(Some(&extra_perms)), - describe_extra_perms(folder_extra_perms.as_ref()), - describe_authed(authed) - ))); - } else { - return Err(Error::NotAuthorized(format!( - "Variable exists but you don't have access to it:\nvariable perms: {}\nauthed as: {}", - describe_extra_perms(Some(&extra_perms)), - describe_authed(authed) - ))); - } + .await?, + )) } async fn exists_variable( @@ -724,6 +795,151 @@ pub struct NewOAuthAccount { pub cc_token_url: Option<String>, pub mcp_server_url: Option<String>, pub scopes: Option<Vec<String>>, + /// Issued by the workspace's own OAuth app for the service named by `client`, which is then + /// what refreshes it. A wrong flag only breaks this account's refresh: a refresh token works + /// with the client that issued it alone. + pub is_workspace_integration: bool, +} + +async fn insert_account( + tx: &mut sqlx::PgConnection, + w_id: &str, + a: NewOAuthAccount, +) -> Result<i32> { + Ok(sqlx::query_scalar!( + "INSERT INTO account (workspace_id, client, expires_at, refresh_token, grant_type, cc_client_id, cc_client_secret, cc_token_url, mcp_server_url, scopes, is_workspace_integration) VALUES ($1, $2, now() + ($3 || ' seconds')::interval, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING id", + w_id, + a.client, + a.expires_in.to_string(), + a.refresh_token, + a.grant_type, + a.cc_client_id, + a.cc_client_secret, + a.cc_token_url, + a.mcp_server_url, + a.scopes.as_deref(), + a.is_workspace_integration + ) + .fetch_one(&mut *tx) + .await?) +} + +/// Delete an account once no variable links it any more. Any variable can link any account, so +/// another one may still hold it; the check needs `db`, since a caller's own transaction does not +/// see variables it cannot read. +pub async fn delete_unlinked_account(db: &DB, workspace_id: &str, account_id: Option<i32>) { + let Some(account_id) = account_id else { + return; + }; + if let Err(e) = sqlx::query!( + "DELETE FROM account WHERE workspace_id = $1 AND id = $2 + AND NOT EXISTS (SELECT 1 FROM variable WHERE workspace_id = $1 AND account = $2)", + workspace_id, + account_id, + ) + .execute(db) + .await + { + tracing::error!("Failed to delete account {account_id} in {workspace_id}: {e}"); + } +} + +/// Swaps the token and account of the OAuth variable at `path` in place: its sharing and +/// description, and the resources and triggers pointing at it, stay as they are. The account it +/// held is deleted unless another variable still uses it. Returns the new account's id. +pub async fn replace_variable_account( + authed: ApiAuthed, + db: &DB, + user_db: UserDB, + webhook: &WebhookShared, + w_id: String, + path: String, + value: String, + account: NewOAuthAccount, +) -> Result<i32> { + check_scopes(&authed, || format!("variables:write:{path}"))?; + if let RuleCheckResult::Blocked(msg) = check_deploy_rules( + &w_id, + AuditAuthorable::username(&authed), + &authed.groups, + authed.is_admin, + db, + ) + .await? + { + return Err(Error::PermissionDenied(msg)); + } + let authed = maybe_refresh_folders(&path, &w_id, authed, db).await; + + let mut tx = user_db.begin(&authed).await?; + // Locked before the secret is written, which an external backend does by path: a refresh of + // the old account writes there under the same lock, so it lands either before this token or + // not at all. Row-level security hides a variable the caller may not write. + let old = sqlx::query!( + "SELECT value::text AS \"value!\", account FROM variable + WHERE path = $1 AND workspace_id = $2 FOR UPDATE", + path, + w_id + ) + .fetch_optional(&mut *tx) + .await? + .ok_or_else(|| Error::NotAuthorized(format!("You cannot write the variable at {path}")))?; + let old_ref = is_external_ref_value(&old.value).then_some(old.value.as_str()); + let value = secret_value_to_store( + db, + &w_id, + &path, + value, + false, + "update", + authed.is_admin, + old_ref, + true, + ) + .await?; + + let account_id = insert_account(&mut tx, &w_id, account).await?; + sqlx::query!( + "UPDATE variable SET value = $3, account = $4, edited_by = $5, edited_at = now() + WHERE workspace_id = $1 AND path = $2", + w_id, + path, + value, + account_id, + authed.username, + ) + .execute(&mut *tx) + .await?; + audit_log( + &mut *tx, + &authed, + "variables.update", + ActionKind::Update, + &w_id, + Some(&path), + None, + ) + .await?; + tx.commit().await?; + delete_unlinked_account(db, &w_id, old.account).await; + + handle_deployment_metadata( + &authed.email, + &authed.username, + db, + &w_id, + DeployedObject::Variable { path: path.clone(), parent_path: None }, + Some(format!("Variable '{path}' reconnected")), + true, + None, + ) + .await?; + webhook.send_message( + w_id.clone(), + WebhookMessage::UpdateVariable { workspace: w_id, old_path: path.clone(), new_path: path }, + ); + + Ok(account_id) } /// Creates a variable and, given `account`, the OAuth account it refreshes through, linked in the @@ -793,23 +1009,7 @@ pub async fn create_variable_with_account( let mut tx = user_db.begin(&authed).await?; let account_id = match account { - Some(a) => Some( - sqlx::query_scalar!( - "INSERT INTO account (workspace_id, client, expires_at, refresh_token, grant_type, cc_client_id, cc_client_secret, cc_token_url, mcp_server_url, scopes) VALUES ($1, $2, now() + ($3 || ' seconds')::interval, $4, $5, $6, $7, $8, $9, $10) RETURNING id", - &w_id, - a.client, - a.expires_in.to_string(), - a.refresh_token, - a.grant_type, - a.cc_client_id, - a.cc_client_secret, - a.cc_token_url, - a.mcp_server_url, - a.scopes.as_deref() - ) - .fetch_one(&mut *tx) - .await?, - ), + Some(a) => Some(insert_account(&mut tx, &w_id, a).await?), None => None, }; @@ -974,6 +1174,11 @@ async fn delete_variable( ) .fetch_optional(&mut *tx) .await?; + // The resource at the same path goes with the variable, so a scoped token needs write access + // to it too. Erroring rolls the whole delete back. + if deleted_linked_resource.is_some() { + check_scopes(&authed, || format!("resources:write:{}", path))?; + } if let Some(var_data) = trash_var { let mut trash_data = serde_json::json!({"row": var_data}); @@ -1164,6 +1369,9 @@ async fn delete_variables_bulk( ) .fetch_all(&mut *tx) .await?; + for rpath in &deleted_resource_paths { + check_scopes(&authed, || format!("resources:write:{}", rpath))?; + } sqlx::query!( "DELETE FROM ws_specific WHERE workspace_id = $1 AND item_kind = 'variable' AND path = ANY($2)", @@ -1243,6 +1451,10 @@ struct EditVariable { deserialize_with = "windmill_common::more_serde::double_option" )] value_valid_until: Option<Option<chrono::DateTime<chrono::Utc>>>, + /// Detaches the OAuth account the variable refreshes through, for a token that no longer + /// comes from it. + #[serde(default)] + unlink_account: bool, } #[derive(Deserialize)] @@ -1293,6 +1505,18 @@ async fn update_variable( sqlb.set_str("path", npath); has_sql_updates = true; } + let mut tx: Transaction<'_, Postgres> = user_db.begin(&authed).await?; + // A reconnect locks the row before writing the secret, so a refresh of the account it + // unlinks cannot land its token after this one (see `replace_variable_account`). + if ns.unlink_account { + sqlx::query_scalar!( + "SELECT 1 FROM variable WHERE path = $1 AND workspace_id = $2 FOR UPDATE", + path, + w_id + ) + .fetch_optional(&mut *tx) + .await?; + } let ns_value_is_none = ns.value.is_none(); // Determine the target path for storing secrets (use new path if provided) let target_path = ns.path.as_deref().unwrap_or(path); @@ -1367,14 +1591,11 @@ async fn update_variable( has_sql_updates = true; } - let mut tx: Transaction<'_, Postgres> = user_db.begin(&authed).await?; - if let Some(npath) = ns.path.clone() { if npath != path { check_path_conflict(&db, &w_id, &npath).await?; require_owner_of_path(&authed, path)?; - // Handle Vault secret rename if the variable is a secret stored in Vault let current_var = sqlx::query!( "SELECT value::text AS \"value!\", is_secret FROM variable WHERE path = $1 AND workspace_id = $2", path, @@ -1383,6 +1604,22 @@ async fn update_variable( .fetch_optional(&mut *tx) .await?; + // Locked so the value written back below is the one stored now, not one a concurrent + // resource write has since replaced. + let linked_resource = sqlx::query_scalar!( + "SELECT value FROM resource WHERE path = $1 AND workspace_id = $2 FOR UPDATE", + path, + w_id + ) + .fetch_optional(&mut *tx) + .await?; + // The resource at the same path moves with the variable. + if linked_resource.is_some() { + check_scopes(&authed, || format!("resources:write:{}", path))?; + check_scopes(&authed, || format!("resources:write:{}", npath))?; + } + + // Handle Vault secret rename if the variable is a secret stored in Vault if let Some(var) = current_var { if var.is_secret && is_http_store_stored_value(&var.value) { return Err(http_store_rename_error(path)); @@ -1405,33 +1642,21 @@ async fn update_variable( } } - let mut v = sqlx::query_scalar!( - "SELECT value FROM resource WHERE path = $1 AND workspace_id = $2", - path, - w_id - ) - .fetch_optional(&mut *tx) - .await? - .flatten(); - - if let Some(old_v) = v { - v = Some(replace_path( - old_v, - &format!("$var:{path}"), - &format!("$var:{npath}"), - )) + if let Some(v) = linked_resource { + let v = v.map(|old_v| { + replace_path(old_v, &format!("$var:{path}"), &format!("$var:{npath}")) + }); + sqlx::query!( + "UPDATE resource SET path = $1, value = $2, edited_at = now() WHERE path = $3 AND workspace_id = $4", + npath, + v, + path, + w_id + ) + .execute(&mut *tx) + .await?; } - sqlx::query!( - "UPDATE resource SET path = $1, value = $2, edited_at = now() WHERE path = $3 AND workspace_id = $4", - npath, - v, - path, - w_id - ) - .execute(&mut *tx) - .await?; - sqlx::query!( "UPDATE native_trigger SET connection_path = $1 WHERE workspace_id = $2 AND connection_path = $3", npath, @@ -1541,6 +1766,21 @@ async fn update_variable( } } + let mut unlinked_account = None; + if ns.unlink_account { + unlinked_account = sqlx::query_scalar!( + "UPDATE variable v SET account = NULL FROM variable o + WHERE o.workspace_id = v.workspace_id AND o.path = v.path + AND v.workspace_id = $1 AND v.path = $2 AND v.account IS NOT NULL + RETURNING o.account", + w_id, + &npath, + ) + .fetch_optional(&mut *tx) + .await? + .flatten(); + } + audit_log( &mut *tx, &authed, @@ -1553,6 +1793,7 @@ async fn update_variable( .await?; tx.commit().await?; + delete_unlinked_account(&db, &w_id, unlinked_account).await; // Detect if this was a rename operation let old_path_if_renamed = if npath != path { Some(path) } else { None }; diff --git a/backend/windmill-trigger-http/src/handler.rs b/backend/windmill-trigger-http/src/handler.rs index 20c51dffb4..0f2add85d6 100644 --- a/backend/windmill-trigger-http/src/handler.rs +++ b/backend/windmill-trigger-http/src/handler.rs @@ -295,15 +295,20 @@ pub async fn create_many_http_triggers( .await .map_err(|err| error_wrapper(&new_http_trigger.config.route_path, err))?; let new = trigger_save_runnables::<HttpTrigger>(new_http_trigger)?; - windmill_api_auth::composed::check_new_hub_paths(&new, &[], &authed, &db, &w_id) - .await - .map_err(|err| match err { - Error::PermissionDenied(msg) => Error::PermissionDenied(format!( - "Error occurred for HTTP route at route path: {}, error: {msg}", - new_http_trigger.config.route_path - )), - err => err, - })?; + let checked = match windmill_api_auth::check_run_scopes(&authed, &new) { + Ok(()) => { + windmill_api_auth::composed::check_new_hub_paths(&new, &[], &authed, &db, &w_id) + .await + } + err => err, + }; + checked.map_err(|err| match err { + Error::PermissionDenied(msg) => Error::PermissionDenied(format!( + "Error occurred for HTTP route at route path: {}, error: {msg}", + new_http_trigger.config.route_path + )), + err => err, + })?; let route_path_key = check_if_route_exist(&db, &new_http_trigger.config, &w_id, None).await?; diff --git a/backend/windmill-trigger-websocket/src/handler.rs b/backend/windmill-trigger-websocket/src/handler.rs index 873cc8c4ea..e3a0c1cc71 100644 --- a/backend/windmill-trigger-websocket/src/handler.rs +++ b/backend/windmill-trigger-websocket/src/handler.rs @@ -4,7 +4,7 @@ use async_trait::async_trait; use itertools::Itertools; use serde_json::value::RawValue; use sqlx::{types::Json as SqlxJson, PgConnection}; -use windmill_api_auth::{check_scopes, ApiAuthed}; +use windmill_api_auth::ApiAuthed; use windmill_common::DB; use windmill_common::{ db::UserDB, @@ -22,25 +22,12 @@ use super::{ WebsocketTrigger, }; -/// A websocket_triggers:write token can configure secondary runnables that the -/// listener later executes under the trigger owner's identity: a `$flow:`/ -/// `$script:` URL resolver and `initial_messages` of kind `runnable_result`. -/// That execution happens in a background task where the reconstructed authed is -/// scopeless (so its check_scopes is a no-op), so enforce run scope here, at -/// create/update time, against the API caller's token. Reading the paths here also -/// refuses, for any caller, one that does not parse. -fn check_secondary_runnable_scopes( - authed: &ApiAuthed, - config: &WebsocketConfigRequest, -) -> Result<()> { +/// Refuses a `$flow:`/`$script:` URL resolver or `runnable_result` initial message whose path +/// does not parse: `config_runnables` leaves those out, so the save's run-scope check never sees +/// them. +fn check_secondary_runnables_parse(config: &WebsocketConfigRequest) -> Result<()> { for runnable in secondary_runnables(&config.url, config.initial_messages.as_deref()) { - let runnable = runnable?; - let kind = if runnable.is_flow() { - "flows" - } else { - "scripts" - }; - check_scopes(authed, || format!("jobs:run:{kind}:{}", runnable.path()))?; + runnable?; } Ok(()) } @@ -157,7 +144,7 @@ impl TriggerCrud for WebsocketTrigger { w_id: &str, trigger: TriggerData<Self::TriggerConfigRequest>, ) -> Result<()> { - check_secondary_runnable_scopes(authed, &trigger.config)?; + check_secondary_runnables_parse(&trigger.config)?; let resolved_edited_by = trigger.base.resolve_edited_by(authed); let resolved_permissioned_as = trigger.base.resolve_permissioned_as(authed); let filters = trigger @@ -237,7 +224,7 @@ impl TriggerCrud for WebsocketTrigger { path: &str, trigger: TriggerData<Self::TriggerConfigRequest>, ) -> Result<()> { - check_secondary_runnable_scopes(authed, &trigger.config)?; + check_secondary_runnables_parse(&trigger.config)?; let resolved_edited_by = trigger.base.resolve_edited_by(authed); let resolved_permissioned_as = trigger.base.resolve_permissioned_as(authed); let filters = trigger diff --git a/backend/windmill-trigger/src/capture.rs b/backend/windmill-trigger/src/capture.rs index 7831adef55..fbce853c11 100644 --- a/backend/windmill-trigger/src/capture.rs +++ b/backend/windmill-trigger/src/capture.rs @@ -99,6 +99,11 @@ pub async fn insert_capture_payload( preprocessor_args: PushArgsOwned, owner: &str, ) -> Result<()> { + // A capture is replayed as its tester's job, so it holds what the trigger would deliver. + let [main_args, preprocessor_args] = [main_args, preprocessor_args].map(|mut args| { + args.sanitize_untrusted(); + args.omit_untrusted_interpolation() + }); sqlx::query!( r#" INSERT INTO diff --git a/backend/windmill-trigger/src/global_handler.rs b/backend/windmill-trigger/src/global_handler.rs index cae38d935d..056a65966a 100644 --- a/backend/windmill-trigger/src/global_handler.rs +++ b/backend/windmill-trigger/src/global_handler.rs @@ -173,6 +173,9 @@ pub async fn resume_suspended_trigger_jobs( let l = jobs.len(); let mut unsuspended_in_place = 0; + // A re-pushed job runs as the trigger does, as it would have had it not been parked, not as + // whoever resumes it. + let mut trigger_authed: Option<ApiAuthed> = None; for job in jobs { // If job was created after trigger was edited, simply update it to unsuspend @@ -214,12 +217,33 @@ pub async fn resume_suspended_trigger_jobs( } else { // Job was created before trigger edit - delete and repush with new configuration // Pass the transaction to trigger_runnable_inner so everything is in the same transaction + let run_as = match &trigger_authed { + Some(a) => a.clone(), + None => { + let email = windmill_common::users::get_email_from_permissioned_as( + &trigger.permissioned_as, + &w_id, + &db, + ) + .await?; + let a = windmill_api_auth::fetch_api_authed_from_permissioned_as( + trigger.permissioned_as.clone(), + email, + &w_id, + &db, + Some(format!("{}-{}", trigger_kind, trigger_path)), + ) + .await?; + trigger_authed = Some(a.clone()); + a + } + }; let (_uuid, _delete_after_use, _early_return, _has_failure_module, tx_o) = trigger_runnable_inner( &db, Some(tx), Some(user_db.clone()), - authed.clone(), + run_as, ChosenBy::Deployed, &w_id, &windmill_common::runnable_ref::RunnableRef::from_path( diff --git a/backend/windmill-trigger/src/handler.rs b/backend/windmill-trigger/src/handler.rs index 512ce51f82..edf874e1e2 100644 --- a/backend/windmill-trigger/src/handler.rs +++ b/backend/windmill-trigger/src/handler.rs @@ -13,8 +13,7 @@ use sql_builder::{bind::Bind, SqlBuilder}; use sqlx::{FromRow, PgConnection}; use std::fmt::Debug; use windmill_api_auth::{ - build_scope_path_predicate, check_scopes, - composed::check_new_hub_paths, + build_scope_path_predicate, check_run_scopes, check_scopes, composed::check_new_hub_paths, ApiAuthed, }; use windmill_common::{ @@ -597,6 +596,7 @@ async fn create_trigger<T: TriggerCrud>( .validate_new(&db, &workspace_id, &new_trigger.config) .await?; let new = trigger_save_runnables::<T>(&new_trigger)?; + check_run_scopes(&authed, &new)?; check_new_hub_paths(&new, &[], &authed, &db, &workspace_id).await?; let mut tx = user_db.begin(&authed).await?; @@ -872,6 +872,7 @@ async fn update_trigger<T: TriggerCrud>( .validate_edit(&db, &workspace_id, &edit_trigger.config, path) .await?; let new_runnables = trigger_save_runnables::<T>(&edit_trigger)?; + check_run_scopes(&authed, &new_runnables)?; let mut tx = user_db.begin(&authed).await?; diff --git a/backend/windmill-types/src/flow_status.rs b/backend/windmill-types/src/flow_status.rs index 4231343080..bb8080cdf2 100644 --- a/backend/windmill-types/src/flow_status.rs +++ b/backend/windmill-types/src/flow_status.rs @@ -114,6 +114,9 @@ pub struct Iterator { pub itered: Option<Vec<Box<serde_json::value::RawValue>>>, #[serde(skip_serializing_if = "Option::is_none")] pub itered_len: Option<usize>, + /// The loop's `failure_threshold`, evaluated once when the loop starts. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub failure_threshold: Option<u32>, } #[derive(Serialize, Deserialize, Debug, Clone)] @@ -136,6 +139,13 @@ pub enum BranchChosen { pub struct Approval { pub resume_id: u16, pub approver: String, + /// Kept on the step because the resume rows that also record it are deleted with the run. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub approved_at: Option<chrono::DateTime<chrono::Utc>>, + /// False for a rejection the flow continued past (`continue_on_disapprove_timeout`): the + /// step succeeds and lists who rejected it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub approved: Option<bool>, } #[derive(Serialize, Deserialize, Debug, Clone)] @@ -210,6 +220,7 @@ struct UntaggedFlowStatusModule { type_: String, id: Option<String>, count: Option<u16>, + home: Option<HomeListing>, progress: Option<u8>, job: Option<Uuid>, iterator: Option<Iterator>, @@ -266,6 +277,12 @@ pub enum AgentAction { }, } +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct HomeListing { + #[serde(skip_serializing_if = "Option::is_none")] + pub step_summary: Option<String>, +} + #[derive(Serialize, Deserialize, Debug, Clone)] pub struct ApprovalCall { pub function_name: String, @@ -282,6 +299,10 @@ pub enum FlowStatusModule { id: String, count: u16, job: Uuid, + /// Set while waiting on an approval step with `show_on_home`, so the Home list of + /// approvals reads it here rather than in each run's flow definition. + #[serde(skip_serializing_if = "Option::is_none")] + home: Option<HomeListing>, }, WaitingForExecutor { id: String, @@ -385,6 +406,7 @@ impl<'de> Deserialize<'de> for FlowStatusModule { job: untagged .job .ok_or_else(|| serde::de::Error::missing_field("job"))?, + home: untagged.home, }), "WaitingForExecutor" => Ok(FlowStatusModule::WaitingForExecutor { id: untagged diff --git a/backend/windmill-types/src/flows.rs b/backend/windmill-types/src/flows.rs index 0d6ef433a3..e217199ec1 100644 --- a/backend/windmill-types/src/flows.rs +++ b/backend/windmill-types/src/flows.rs @@ -604,6 +604,10 @@ pub struct Suspend { pub continue_on_disapprove_timeout: Option<bool>, #[serde(skip_serializing_if = "Option::is_none")] pub skin: Option<ApprovalSkin>, + /// Lists the waiting step on its approvers' Home. Off unless set: an approval announced + /// elsewhere (a resume link sent to a chat) would otherwise sit there unanswered. + #[serde(skip_serializing_if = "Option::is_none")] + pub show_on_home: Option<bool>, } /// How an approval request is presented, on the approval page and in Slack/Teams messages. @@ -1150,6 +1154,9 @@ pub enum FlowModuleValue { /// viewers show for that iteration. Never fails the iteration. #[serde(skip_serializing_if = "Option::is_none")] iteration_label: Option<InputTransform>, + /// With `skip_failures`, the loop fails as soon as this many iterations have failed. + #[serde(skip_serializing_if = "Option::is_none")] + failure_threshold: Option<InputTransform>, }, WhileloopFlow { modules: Vec<FlowModule>, @@ -1163,6 +1170,9 @@ pub enum FlowModuleValue { max_iterations: Option<u32>, #[serde(skip_serializing_if = "Option::is_none")] max_duration_secs: Option<u32>, + /// With `skip_failures`, the loop fails as soon as this many iterations have failed. + #[serde(skip_serializing_if = "Option::is_none")] + failure_threshold: Option<InputTransform>, }, BranchOne { branches: Vec<Branch>, @@ -1277,6 +1287,8 @@ struct UntaggedFlowModuleValue { pass_flow_input_directly: Option<bool>, squash: Option<bool>, iteration_label: Option<InputTransform>, + #[serde(default, deserialize_with = "raw_value_to_input_transform::<_, u32>")] + failure_threshold: Option<InputTransform>, max_iterations: Option<u32>, max_duration_secs: Option<u32>, #[serde(flatten)] @@ -1322,6 +1334,7 @@ impl<'de> Deserialize<'de> for FlowModuleValue { parallelism: untagged.parallelism, squash: untagged.squash, iteration_label: untagged.iteration_label, + failure_threshold: untagged.failure_threshold, }), "whileloopflow" => Ok(FlowModuleValue::WhileloopFlow { modules: untagged @@ -1332,6 +1345,7 @@ impl<'de> Deserialize<'de> for FlowModuleValue { squash: untagged.squash, max_iterations: untagged.max_iterations, max_duration_secs: untagged.max_duration_secs, + failure_threshold: untagged.failure_threshold, }), "branchone" => Ok(FlowModuleValue::BranchOne { branches: untagged diff --git a/backend/windmill-worker-volumes/src/lib.rs b/backend/windmill-worker-volumes/src/lib.rs index f167676ea4..5fa3467e30 100644 --- a/backend/windmill-worker-volumes/src/lib.rs +++ b/backend/windmill-worker-volumes/src/lib.rs @@ -12,6 +12,41 @@ use std::path::PathBuf; pub const MAX_VOLUMES_PER_JOB: usize = 10; +/// Object requests a pull or a sync-back keeps in flight for one volume. +pub const VOLUME_TRANSFER_CONCURRENCY: usize = 16; + +/// An upload holds its whole file in memory, so a sync-back bounds the bytes of the uploads in +/// flight as well as their count: a file at least this large is uploaded alone. +pub const VOLUME_UPLOAD_BYTES_IN_FLIGHT: u64 = 256 * 1024 * 1024; + +/// Deletes `paths` concurrently, an object already gone counting as deleted. Returns how many +/// were deleted, or the first failure and how many failed: a delete is never assumed to succeed. +pub async fn delete_objects( + client: &dyn object_store::ObjectStore, + paths: Vec<object_store::path::Path>, +) -> Result<usize, String> { + use futures::StreamExt; + let results: Vec<Result<(), String>> = futures::stream::iter(paths) + .map(|path| async move { + match client.delete(&path).await { + Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()), + Err(e) => Err(format!("{path}: {e}")), + } + }) + .buffer_unordered(VOLUME_TRANSFER_CONCURRENCY) + .collect() + .await; + let total = results.len(); + let failures: Vec<String> = results.into_iter().filter_map(Result::err).collect(); + match failures.first() { + None => Ok(total), + Some(first) => Err(format!( + "failed to delete {} of {total} removed file(s), first: {first}", + failures.len() + )), + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FileEntry { pub size: u64, @@ -25,7 +60,10 @@ pub struct FileEntry { pub fn compute_md5_hex(data: &[u8]) -> String { use md5::{Digest, Md5}; - let result = Md5::digest(data); + md5_digest_hex(&Md5::digest(data)) +} + +pub fn md5_digest_hex(result: &[u8]) -> String { const HEX: &[u8; 16] = b"0123456789abcdef"; let mut hex = String::with_capacity(32); for &b in result.iter() { @@ -112,6 +150,7 @@ pub struct SyncStats { pub file_count: usize, pub uploaded: usize, pub skipped: usize, + pub deleted: usize, } pub fn validate_volume_name(name: &str) -> Result<(), String> { diff --git a/backend/windmill-worker/src/ai/tools.rs b/backend/windmill-worker/src/ai/tools.rs index efa37c3867..9be8630868 100644 --- a/backend/windmill-worker/src/ai/tools.rs +++ b/backend/windmill-worker/src/ai/tools.rs @@ -7,6 +7,7 @@ use crate::ai::utils::{ }; use crate::common::{get_root_job_id, OccupancyMetrics}; use crate::result_processor::handle_non_flow_job_error; +use crate::worker::{create_span_with_name, log_context_for_job, record_job_span_status}; use crate::worker_flow::{ evaluate_input_transform, raw_script_to_payload, resolve_flow_step_tag, script_to_payload, JobPayloadWithTag, @@ -22,6 +23,7 @@ use std::{ sync::Arc, time::{Duration, Instant}, }; +use tracing::Instrument; use uuid::Uuid; use windmill_ai::{ai_types::OpenAIToolCall, query_builder::StreamEventSink, types::*}; use windmill_common::jobs::JobPayload; @@ -1147,27 +1149,44 @@ fn spawn_local_tool( ); let job_dir = create_job_dir(&worker_dir_spawn, tool_job.id).await; - handle_queued_job( - tool_job.clone(), - None, - None, - None, - None, - &conn_spawn, - &client_spawn, - &hostname_spawn, + let span = create_span_with_name( + &tool_job, &worker_name_spawn, - &worker_dir_spawn, - &job_dir, - None, - &base_internal_url_spawn, - job_completed_tx, - &mut occupancy_metrics_spawn, - &mut killpill_rx_spawn, - None, - None, - #[cfg(feature = "benchmark")] - &mut bench_spawn, + Some(&hostname_spawn), + "job", + ); + let log_ctx = + log_context_for_job(&tool_job, &worker_name_spawn, Some(&hostname_spawn)); + windmill_common::log_context::with_log_context( + log_ctx, + async { + let result = Box::pin(handle_queued_job( + tool_job.clone(), + None, + None, + None, + None, + &conn_spawn, + &client_spawn, + &hostname_spawn, + &worker_name_spawn, + &worker_dir_spawn, + &job_dir, + None, + &base_internal_url_spawn, + job_completed_tx, + &mut occupancy_metrics_spawn, + &mut killpill_rx_spawn, + None, + None, + #[cfg(feature = "benchmark")] + &mut bench_spawn, + )) + .await; + record_job_span_status(&result); + result + } + .instrument(span), ) .await } diff --git a/backend/windmill-worker/src/r_executor.rs b/backend/windmill-worker/src/r_executor.rs index 4220feba91..bcf94ba603 100644 --- a/backend/windmill-worker/src/r_executor.rs +++ b/backend/windmill-worker/src/r_executor.rs @@ -10,6 +10,7 @@ use uuid::Uuid; use windmill_common::{ client::AuthedClient, error::Error, + sensitive_log_masks, utils::calculate_hash, worker::{write_file, Connection, RlangAnnotations}, }; @@ -26,11 +27,11 @@ use crate::{ }, get_proxy_envs_for_lang, get_run_proxy_envs, handle_child::{self}, - is_sandboxing_enabled, nsjail_clone_newnet, + is_sandboxing_enabled, nsjail_clone_newnet, read_ee_registry_with_workspace_override, universal_pkg_installer::{ par_install_language_dependencies_seq, DependencyGraph, InstallDeps, RequiredDependency, }, - DISABLE_NUSER, NSJAIL_AVAILABLE, NSJAIL_PATH, PATH_ENV, PROXY_ENVS, R_CACHE_DIR, + CRAN_REPO_URL, DISABLE_NUSER, NSJAIL_AVAILABLE, NSJAIL_PATH, PATH_ENV, PROXY_ENVS, R_CACHE_DIR, TRACING_PROXY_CA_CERT_PATH, WIN_ENVS, }; use windmill_common::scripts::ScriptLang; @@ -47,6 +48,38 @@ lazy_static::lazy_static! { }; } +const DEFAULT_CRAN_REPO_URL: &str = "https://cloud.r-project.org"; + +/// The CRAN mirror configured for this workspace (or instance), if any. +/// +/// renv echoes the full repository URL when a download fails, so credentials in it are +/// registered with the job's log masks before any R process sees the URL. +async fn configured_cran_repo_url(job_id: &Uuid, w_id: &str, conn: &Connection) -> Option<String> { + let repo = read_ee_registry_with_workspace_override( + CRAN_REPO_URL.read().await.clone(), + "cran_repo_url", + "CRAN repository url", + job_id, + w_id, + conn, + ) + .await + .map(|s| s.trim().to_string())?; + if let Ok(parsed) = url::Url::parse(&repo) { + if let Some(password) = parsed.password() { + sensitive_log_masks::register_secret_for_job( + *job_id, + &format!("{}:{}", parsed.username(), password), + ); + sensitive_log_masks::register_secret_for_job(*job_id, password); + } else if !parsed.username().is_empty() { + // A bare userinfo is commonly a token. + sensitive_log_masks::register_secret_for_job(*job_id, parsed.username()); + } + } + Some(repo) +} + const NSJAIL_CONFIG_RUN_R_CONTENT: &str = include_str!("../nsjail/run.r.config.proto"); const NSJAIL_CONFIG_INSTALL_R_CONTENT: &str = include_str!("../nsjail/install.r.config.proto"); @@ -208,8 +241,14 @@ pub async fn resolve<'a>( } } - // Check cache - let req_hash = format!("r-{}", calculate_hash(&packages)); + let custom_repo = configured_cran_repo_url(job_id, w_id, conn).await; + + // A mirror resolves its own versions, so it must not share a cache entry with CRAN. + let req_hash = match &custom_repo { + Some(repo) => format!("r-{}", calculate_hash(&format!("{packages}\n#repo:{repo}"))), + None => format!("r-{}", calculate_hash(&packages)), + }; + let repo_url = custom_repo.as_deref().unwrap_or(DEFAULT_CRAN_REPO_URL); if let Some(db) = conn.as_sql() { if let Some(cached) = sqlx::query_scalar!( "SELECT lockfile FROM pip_resolution_cache WHERE hash = $1", @@ -235,7 +274,7 @@ pub async fn resolve<'a>( // Disable renv's own package cache — Windmill manages its own install cache. let resolve_script = format!( r#"options( - repos = c(CRAN = "https://cloud.r-project.org"), + repos = c(CRAN = "{repo_url}"), renv.verbose = {verbose_r}, renv.config.cache.enabled = FALSE, renv.config.restart.enabled = FALSE, @@ -247,6 +286,7 @@ suppressMessages(renv::install(prompt = FALSE)) suppressMessages(renv::snapshot(type = "implicit", prompt = FALSE)) "#, verbose_r = if verbose { "TRUE" } else { "FALSE" }, + repo_url = escape_r_double_quoted(repo_url), ); let mut file = File::create(format!("{}/resolve.r", job_dir)).await?; @@ -290,6 +330,9 @@ suppressMessages(renv::snapshot(type = "implicit", prompt = FALSE)) let mut lock_file = File::open(&lock_path).await?; let mut lock = String::new(); lock_file.read_to_string(&mut lock).await?; + if custom_repo.is_some() { + lock = strip_repo_credentials(lock); + } // Cache the lockfile if let Some(db) = conn.as_sql() { @@ -315,6 +358,41 @@ suppressMessages(renv::snapshot(type = "implicit", prompt = FALSE)) Ok(lock) } +/// `renv::snapshot` records the `repos` option in the lockfile, which is stored as the +/// script's lock and readable by anyone who can see the script: credentials in the mirror +/// URL must not reach it. `install` takes the credentialed URL from the setting instead. +fn strip_repo_credentials(lock: String) -> String { + let Ok(mut json) = serde_json::from_str::<serde_json::Value>(&lock) else { + return lock; + }; + let mut changed = false; + if let Some(repos) = json + .get_mut("R") + .and_then(|r| r.get_mut("Repositories")) + .and_then(|r| r.as_array_mut()) + { + for repo in repos { + let Some(url) = repo.get("URL").and_then(|u| u.as_str()) else { + continue; + }; + let Ok(mut parsed) = url::Url::parse(url) else { + continue; + }; + if parsed.username().is_empty() && parsed.password().is_none() { + continue; + } + let _ = parsed.set_username(""); + let _ = parsed.set_password(None); + repo["URL"] = serde_json::Value::String(parsed.to_string()); + changed = true; + } + } + if !changed { + return lock; + } + serde_json::to_string_pretty(&json).unwrap_or(lock) +} + struct RenvPackage { name: String, version: String, @@ -401,7 +479,7 @@ fn parse_renv_lock(lockfile: &str) -> Result<Vec<RenvPackage>, Error> { let repo_url = repo_urls .get(repo_name) .cloned() - .unwrap_or_else(|| "https://cloud.r-project.org".to_string()); + .unwrap_or_else(|| DEFAULT_CRAN_REPO_URL.to_string()); let mut dependencies = vec![]; if let Some(imports) = pkg.get("Imports").and_then(|v| v.as_array()) { @@ -440,11 +518,15 @@ async fn install<'a>( return Ok(lib_path); } + // The configured mirror wins over the URL recorded in the lockfile, so a lockfile + // resolved against CRAN still installs on an instance that can only reach the mirror. + let custom_repo = + configured_cran_repo_url(&args.job.id, &args.job.workspace_id, args.conn).await; + #[derive(Clone, Debug)] struct RPackagePayload { pkg: String, version: String, - #[allow(dead_code)] repo_url: String, } @@ -467,7 +549,9 @@ async fn install<'a>( custom_payload: RPackagePayload { pkg: renv_pkg.name.clone(), version: renv_pkg.version.clone(), - repo_url: renv_pkg.repo_url.clone(), + repo_url: custom_repo + .clone() + .unwrap_or_else(|| renv_pkg.repo_url.clone()), }, }, renv_pkg.dependencies.clone(), @@ -535,12 +619,13 @@ async fn install<'a>( .args(&[ "-e", &format!( - r#"options(renv.verbose = {verbose_r}, renv.config.install.verbose = {install_verbose_r}, renv.config.restart.enabled = FALSE); renv::install("{pkg}@{version}", library = "{lib}", dependencies = FALSE)"#, + r#"options(repos = c(CRAN = "{repo}"), renv.verbose = {verbose_r}, renv.config.install.verbose = {install_verbose_r}, renv.config.restart.enabled = FALSE); renv::install("{pkg}@{version}", library = "{lib}", dependencies = FALSE)"#, verbose_r = verbose_r, install_verbose_r = install_verbose_r, pkg = escape_r_double_quoted(&dependency.custom_payload.pkg), version = escape_r_double_quoted(&dependency.custom_payload.version), lib = escape_r_double_quoted(&install_lib), + repo = escape_r_double_quoted(&dependency.custom_payload.repo_url), ), // install.packages fallback (no version pinning): // &format!( @@ -791,7 +876,9 @@ tryCatch({{ #[cfg(test)] mod tests { - use super::{escape_r_double_quoted, parse_renv_lock, validate_renv_package}; + use super::{ + escape_r_double_quoted, parse_renv_lock, strip_repo_credentials, validate_renv_package, + }; #[test] fn test_validate_renv_package_accepts_real() { @@ -849,4 +936,16 @@ mod tests { assert_eq!(pkgs.len(), 1); assert_eq!(pkgs[0].name, "ggplot2"); } + + #[test] + fn test_strip_repo_credentials() { + let lock = r#"{"R":{"Version":"4.4.1","Repositories":[{"Name":"CRAN","URL":"https://u:s3cret@nexus.example.com/repository/cran"}]},"Packages":{}}"#; + let stripped = strip_repo_credentials(lock.to_string()); + assert!(!stripped.contains("s3cret") && !stripped.contains("u:")); + assert!(stripped.contains("https://nexus.example.com/repository/cran")); + + let clean = + r#"{"R":{"Repositories":[{"Name":"CRAN","URL":"https://cloud.r-project.org"}]}}"#; + assert_eq!(strip_repo_credentials(clean.to_string()), clean); + } } diff --git a/backend/windmill-worker/src/volume_oss.rs b/backend/windmill-worker/src/volume_oss.rs index 3736e83485..c5e32fd8e1 100644 --- a/backend/windmill-worker/src/volume_oss.rs +++ b/backend/windmill-worker/src/volume_oss.rs @@ -3,6 +3,7 @@ pub(crate) use crate::volume_ee::*; #[cfg(not(feature = "private"))] #[cfg(feature = "parquet")] +#[derive(Default)] pub(crate) struct LeaseRenewalGuard(pub Option<tokio::task::JoinHandle<()>>); #[cfg(not(feature = "private"))] @@ -94,6 +95,7 @@ pub(crate) async fn sync_volumes_sql_worker( _worker_name: &str, _conn: &windmill_common::worker::Connection, _job_succeeded: bool, + _lease_renewal: LeaseRenewalGuard, ) { } @@ -108,5 +110,6 @@ pub(crate) async fn sync_volumes_http_worker( _worker_name: &str, _conn: &windmill_common::worker::Connection, _job_succeeded: bool, + _lease_renewal: LeaseRenewalGuard, ) { } diff --git a/backend/windmill-worker/src/worker.rs b/backend/windmill-worker/src/worker.rs index 2333585c90..eb0d6df8c5 100644 --- a/backend/windmill-worker/src/worker.rs +++ b/backend/windmill-worker/src/worker.rs @@ -711,6 +711,7 @@ lazy_static::lazy_static! { .and_then(|x| x.parse::<bool>().ok()) .unwrap_or(false)); pub static ref RUBY_REPOS: Arc<RwLock<Option<Vec<url::Url>>>> = Arc::new(RwLock::new(None)); + pub static ref CRAN_REPO_URL: Arc<RwLock<Option<String>>> = Arc::new(RwLock::new(None)); pub static ref CARGO_REGISTRIES: Arc<RwLock<Option<String>>> = Arc::new(RwLock::new(None)); pub static ref WORKSPACE_REGISTRIES: Arc<RwLock<Option<WorkspaceRegistryMap>>> = Arc::new(RwLock::new(None)); @@ -7072,7 +7073,7 @@ mount {{ states: Vec::new(), writable: Vec::new(), client: None, - lease_renewal: crate::volume_oss::LeaseRenewalGuard(None), + lease_renewal: Default::default(), }; #[cfg(feature = "parquet")] @@ -7617,11 +7618,9 @@ mount {{ // Volume sync-back and lease release #[cfg(feature = "parquet")] if !volume_setup.states.is_empty() { - // Stop lease renewal before sync-back - volume_setup.lease_renewal.0.take().map(|h| h.abort()); - - if let Some(ref vol_client) = volume_setup.client { - if let Connection::Sql(db) = conn { + let lease_renewal = std::mem::take(&mut volume_setup.lease_renewal); + match (conn, volume_setup.client.as_ref()) { + (Connection::Sql(db), Some(vol_client)) => { Box::pin(crate::volume_oss::sync_volumes_sql_worker( &volume_setup.states, &volume_setup.writable, @@ -7632,23 +7631,25 @@ mount {{ worker_name, conn, result.is_ok(), + lease_renewal, )) .await; } - } - - if let Connection::Http(http) = conn { - Box::pin(crate::volume_oss::sync_volumes_http_worker( - &volume_setup.states, - &volume_setup.writable, - http, - &job.workspace_id, - job.id, - worker_name, - conn, - result.is_ok(), - )) - .await; + (Connection::Http(http), _) => { + Box::pin(crate::volume_oss::sync_volumes_http_worker( + &volume_setup.states, + &volume_setup.writable, + http, + &job.workspace_id, + job.id, + worker_name, + conn, + result.is_ok(), + lease_renewal, + )) + .await; + } + (Connection::Sql(_), None) => {} } // Clean up absolute-path symlinks created by setup_volume_mount_paths diff --git a/backend/windmill-worker/src/worker_flow.rs b/backend/windmill-worker/src/worker_flow.rs index d704c103e9..28920820fd 100644 --- a/backend/windmill-worker/src/worker_flow.rs +++ b/backend/windmill-worker/src/worker_flow.rs @@ -41,7 +41,8 @@ use windmill_common::db::Authed; use windmill_common::flow_conversations::{add_message_to_conversation_tx, MessageType}; use windmill_common::flow_status::{ ApprovalConditions, ContinuedOnError, FlowJobDuration, FlowJobsDuration, - FlowStatusModuleWParent, Iterator as FlowIterator, JobResult, MAX_CONTINUED_ON_ERROR, + FlowStatusModuleWParent, HomeListing, Iterator as FlowIterator, JobResult, + MAX_CONTINUED_ON_ERROR, }; use windmill_common::flows::{add_virtual_items_if_necessary, Branch, FlowNodeId, StopAfterIf}; use windmill_common::jobs::{ @@ -434,6 +435,20 @@ async fn evaluate_stop_after_all_iters_if( Ok(()) } +const FAILURE_THRESHOLD_ERROR: &str = "FailureThresholdReached"; +const FAILURE_THRESHOLD_CANCELER: &str = "failure threshold"; + +fn failure_threshold_message(threshold: u32, parallel: bool) -> String { + let s = if threshold == 1 { "" } else { "s" }; + let mut message = + format!("Loop stopped after {threshold} failed iteration{s}, its failure threshold"); + if parallel { + message + .push_str(". Iterations already running finished; those not yet started were canceled"); + } + message +} + fn result_has_recover_true(nresult: Arc<Box<RawValue>>) -> bool { let recover = serde_json::from_str::<RecoveryObject>(nresult.get()); return recover.map(|r| r.recover.unwrap_or(false)).unwrap_or(false); @@ -605,30 +620,41 @@ pub async fn update_flow_status_after_job_completion_internal( // "UPDATE FLOW STATUS 2: {module_step:#?} {module_status:#?} {old_status:#?} " // ); - let (is_loop, skip_loop_failures, parallelism, parallel_loop, loop_bounds) = - if let FlowStatusModule::InProgress { iterator: Some(_), parallel, .. } = module_status - { - let value = current_module - .as_ref() - .and_then(|x| x.get_value_with_skip_failures().ok()); - ( - true, - value - .as_ref() - .and_then(|x| x.skip_failures) - .unwrap_or(false), - value.as_ref().and_then(|x| x.parallelism.clone()), - *parallel, - value.map(|x| { - ( - x.max_iterations.filter(|m| *m > 0), - x.max_duration_secs.filter(|m| *m > 0), - ) - }), - ) - } else { - (false, false, None, false, None) - }; + let ( + is_loop, + skip_loop_failures, + failure_threshold, + parallelism, + parallel_loop, + loop_bounds, + ) = if let FlowStatusModule::InProgress { iterator: Some(iterator), parallel, .. } = + module_status + { + let value = current_module + .as_ref() + .and_then(|x| x.get_value_with_skip_failures().ok()); + let skip_failures = value + .as_ref() + .and_then(|x| x.skip_failures) + .unwrap_or(false); + ( + true, + skip_failures, + iterator + .failure_threshold + .filter(|t| skip_failures && *t > 0), + value.as_ref().and_then(|x| x.parallelism.clone()), + *parallel, + value.map(|x| { + ( + x.max_iterations.filter(|m| *m > 0), + x.max_duration_secs.filter(|m| *m > 0), + ) + }), + ) + } else { + (false, false, None, None, false, None) + }; let (is_branch_all, parallel_branchall) = match module_status { FlowStatusModule::InProgress { branchall: Some(_), parallel, .. } => (true, *parallel), @@ -784,7 +810,7 @@ pub async fn update_flow_status_after_job_completion_internal( // A while loop that reached its iteration or duration bound without its stop condition // being met fails. The loop's start is the first iteration's start, which the module // status persists, so the duration bound holds across worker restarts. - let loop_exhausted_msg = match (module_status, loop_bounds) { + let loop_exhausted_msg = || match (module_status, loop_bounds) { ( FlowStatusModule::InProgress { iterator: Some(FlowIterator { index, .. }), @@ -802,7 +828,7 @@ pub async fn update_flow_status_after_job_completion_internal( .or_else(|| flow_job_duration.as_ref().map(|d| d.started_at)); let elapsed_secs = started_at.map(|s| (chrono::Utc::now() - s).num_milliseconds() as f64 / 1000.0); - if max_iterations.is_some_and(|m| iterations >= m as usize) { + let message = if max_iterations.is_some_and(|m| iterations >= m as usize) { Some(format!( "While loop reached its maximum of {iterations} iterations without its stop condition being met" )) @@ -813,18 +839,44 @@ pub async fn update_flow_status_after_job_completion_internal( )), _ => None, } - } + }; + message.map(|m| ("LoopExhausted", m)) } _ => None, }; - let loop_exhausted_err = loop_exhausted_msg.as_ref().map(|message| { + // A sequential loop stops at the iteration that reaches its failure threshold. + let threshold_msg = match module_status { + FlowStatusModule::InProgress { + flow_jobs: Some(jobs), + flow_jobs_success: Some(jobs_success), + parallel: false, + .. + } if !success => failure_threshold.and_then(|threshold| { + let failed = jobs + .iter() + .zip(jobs_success) + .filter(|(j, s)| *j != job_id_for_status && **s == Some(false)) + .count() + + 1; + (failed >= threshold as usize).then(|| { + ( + FAILURE_THRESHOLD_ERROR, + failure_threshold_message(threshold, false), + ) + }) + }), + _ => None, + }; + let mut loop_err_msg = threshold_msg.or_else(loop_exhausted_msg); + let loop_error_value = |(name, message): &(&str, String)| { Arc::new(to_raw_value(&serde_json::json!({ - "error": { "name": "LoopExhausted", "message": message } + "error": { "name": name, "message": message } }))) - }); + }; + let mut loop_err = loop_err_msg.as_ref().map(loop_error_value); // skip_failures tolerates failed iterations, not the loop failing as a whole. - let skip_loop_failures = skip_loop_failures && loop_exhausted_err.is_none(); - if loop_exhausted_err.is_some() { + let mut skip_loop_failures = skip_loop_failures && loop_err.is_none(); + if loop_err.is_some() { has_triggered_error_handler = false; } @@ -904,6 +956,34 @@ pub async fn update_flow_status_after_job_completion_internal( )) })?.ok_or_else(|| Error::internal_err(format!("requiring an index in InProgress for flow {flow} at step {}", old_status.step)))?; + // Past the failure threshold, the iterations not started yet are cancelled: + // those no worker has picked up, or that `parallelism` holds back. A + // `suspend` is also an approval, whose iteration already ran a step: the + // child job check keeps it, and any started iteration, out. An iteration a + // worker picked up runs to its end, and the loop fails once all are in. + // The count reads the row this transaction just updated. + if let Some(threshold) = failure_threshold.filter(|_| !success) { + sqlx::query!( + "UPDATE v2_job_queue + SET canceled_by = $3, canceled_reason = $4, scheduled_for = now(), suspend = 0 + WHERE id = ANY($2) AND workspace_id = $5 AND canceled_by IS NULL + AND (suspend > 0 OR NOT running) + AND NOT EXISTS (SELECT 1 FROM v2_job c WHERE c.parent_job = v2_job_queue.id) + AND (SELECT count(*) FROM v2_job_status s, + jsonb_array_elements(s.flow_status->'modules'->$6::int->'flow_jobs_success') e + WHERE s.id = $1 AND e = 'false'::jsonb) >= $7", + flow, + jobs.as_slice(), + FAILURE_THRESHOLD_CANCELER, + format!("the for loop reached its failure threshold of {threshold} failed iterations"), + w_id, + old_status.step, + threshold as i64, + ) + .execute(&mut *tx) + .await?; + } + // let status_for_debug = sqlx::query!( // "SELECT flow_status FROM v2_job_status WHERE id = $1", // flow @@ -1024,6 +1104,20 @@ pub async fn update_flow_status_after_job_completion_internal( } } let mut flow_jobs_duration = success_and_durations.1; + + let threshold_reached = failure_threshold.filter(|t| { + flow_jobs_success.as_ref().is_some_and(|s| { + s.iter().filter(|x| **x == Some(false)).count() >= *t as usize + }) + }); + if let Some(threshold) = threshold_reached { + loop_err_msg = Some(( + FAILURE_THRESHOLD_ERROR, + failure_threshold_message(threshold, true), + )); + loop_err = loop_err_msg.as_ref().map(loop_error_value); + skip_loop_failures = false; + } if let Some(flow_jobs_duration) = flow_jobs_duration.as_mut() { let position = jobs.iter().position(|x| x == job_id_for_status); flow_jobs_duration.set(position, &flow_job_duration); @@ -1102,6 +1196,7 @@ pub async fn update_flow_status_after_job_completion_internal( let new_status = if !(stop_early && stop_early_err_msg.is_some() && !skip_if_stop_early) // if stop_early with error and NOT skip_if_stopped, mark as failure + && loop_err.is_none() && ( skip_loop_failures || sqlx::query_scalar!( @@ -1170,7 +1265,7 @@ pub async fn update_flow_status_after_job_completion_internal( // for parallel branchall and forloop, we do not want to trigger the error handler again at the forloop/branchall node since it was already triggered at the leaf level // so we want to ignore the has_triggered_error_handler flag at the forloop/branchall node and reset it based on if the node is a success or failure - if !success && flow_value.failure_module.is_some() { + if !success && flow_value.failure_module.is_some() && loop_err.is_none() { has_triggered_error_handler = true; } else { has_triggered_error_handler = false; @@ -1225,7 +1320,7 @@ pub async fn update_flow_status_after_job_completion_internal( } } FlowStatusModule::InProgress { - iterator: Some(FlowIterator { index, itered_len, itered }), + iterator: Some(FlowIterator { index, itered_len, itered, .. }), flow_jobs_success, flow_jobs, while_loop, @@ -1240,7 +1335,7 @@ pub async fn update_flow_status_after_job_completion_internal( (*while_loop || *index + 1 < itered_len) && (success || skip_loop_failures) && !stop_early - && loop_exhausted_err.is_none() + && loop_err.is_none() } => { if let Some(jobs) = flow_jobs { @@ -1368,7 +1463,7 @@ pub async fn update_flow_status_after_job_completion_internal( if (success || (flow_jobs.is_some() && (skip_loop_failures || skip_seq_branch_failure))) && !(stop_early && stop_early_err_msg.is_some() && !skip_if_stop_early) - && loop_exhausted_err.is_none() + && loop_err.is_none() { let is_skipped = (stop_early && skip_if_stop_early) || if current_module.as_ref().is_some_and(|m| m.skip_if.is_some()) { @@ -1411,7 +1506,7 @@ pub async fn update_flow_status_after_job_completion_internal( evaluate_retry( &retry, &old_status.retry, - loop_exhausted_err.clone().unwrap_or_else(|| result.clone()), + loop_err.clone().unwrap_or_else(|| result.clone()), Marc::new(args), resolved_flow_env.as_deref(), Some(client), @@ -1427,8 +1522,7 @@ pub async fn update_flow_status_after_job_completion_internal( job: *job_id_for_status, }); } - if (stop_early && stop_early_err_msg.is_some()) || loop_exhausted_err.is_some() - { + if (stop_early && stop_early_err_msg.is_some()) || loop_err.is_some() { // if stop_early with error message, we need to set explictely success to false as this function was called with success = true as the job succeeded success = false; } @@ -1470,8 +1564,8 @@ pub async fn update_flow_status_after_job_completion_internal( ))); } - if loop_exhausted_err.is_some() { - nresult = loop_exhausted_err.clone(); + if loop_err.is_some() { + nresult = loop_err.clone(); } let step_counter = if inc_step_counter { @@ -1884,7 +1978,7 @@ pub async fn update_flow_status_after_job_completion_internal( let should_retry = evaluate_retry( retry_config, &old_status.retry, - loop_exhausted_err.clone().unwrap_or_else(|| result.clone()), + loop_err.clone().unwrap_or_else(|| result.clone()), Marc::new(args), resolved_flow_env.as_deref(), Some(client), @@ -1985,8 +2079,9 @@ pub async fn update_flow_status_after_job_completion_internal( let failure_step_recovers = is_failure_step && result_has_recover_true(nresult.clone()); // An error this flow raises on its own (a stop predicate's error message, a while loop - // reaching its bound) is a new failure that no error handler recovered or saw yet. - if stop_early_err_msg.is_some() || loop_exhausted_msg.is_some() { + // reaching its bound, a for loop reaching its failure threshold) is a new failure that + // no error handler recovered or saw yet. + if stop_early_err_msg.is_some() || loop_err_msg.is_some() { recovered_by_child = false; } @@ -3600,6 +3695,7 @@ pub struct ResumeRow { pub approver: Option<String>, pub approved: bool, pub resume_id: i32, + pub created_at: chrono::DateTime<chrono::Utc>, } impl ResumeRow { @@ -4195,7 +4291,7 @@ async fn push_next_flow_job( // Query for both step-level resumes (job = step_id) and flow-level resumes (job = flow_id) // Flow-level resumes allow pre-approvals that can be consumed by any suspend step let resumes = sqlx::query_as::<_, ResumeRow>( - "SELECT value, approver, resume_id, approved FROM resume_job WHERE job = $1 OR job = $2 ORDER BY created_at ASC", + "SELECT value, approver, resume_id, approved, created_at FROM resume_job WHERE job = $1 OR job = $2 ORDER BY created_at ASC", ) .bind(last) .bind(flow_job.id) @@ -4356,7 +4452,9 @@ async fn push_next_flow_job( resume_id: r.resume_id as u16, approver: r .approver.clone() - .unwrap_or_else(|| "unknown".to_string()) + .unwrap_or_else(|| "unknown".to_string()), + approved_at: Some(r.created_at), + approved: Some(r.approved), }) .collect::<Vec<_>>() ), @@ -4399,7 +4497,14 @@ async fn push_next_flow_job( json!(FlowStatusModule::WaitingForEvents { id: status_module.id(), count: required_events, - job: last + job: last, + home: (suspend.show_on_home == Some(true)).then(|| HomeListing { + step_summary: usize::try_from(status.step - 1) + .ok() + .and_then(|i| flow.modules.get(i)) + .and_then(|m| m.summary.clone()) + .filter(|s| !s.is_empty()), + }), }), (required_events.saturating_sub(resume_messages.len() as u16)) as i32, Duration::from_secs( @@ -5672,6 +5777,7 @@ async fn push_next_flow_job( mut flow_jobs_success, mut flow_jobs_duration, flow_jobs_labels, + failure_threshold, .. }, .. @@ -5706,6 +5812,7 @@ async fn push_next_flow_job( index, itered: itered_for_status, itered_len: Some(itered_len), + failure_threshold, }), flow_jobs: Some(flow_jobs), flow_jobs_success, @@ -6009,6 +6116,7 @@ struct ForloopNextIteration { flow_jobs_duration: Option<FlowJobsDuration>, flow_jobs_labels: Option<Vec<Option<String>>>, iteration_label: Option<InputTransform>, + failure_threshold: Option<u32>, new_args: Iter, while_loop: bool, } @@ -6180,6 +6288,50 @@ pub fn get_path(flow_job: &MiniPulledJob, status: &FlowStatus, module: &FlowModu } } +/// A loop's `failure_threshold`, evaluated when the loop starts and kept on its iterator, which +/// later iterations and each iteration's completion read instead of evaluating it again. +async fn loop_failure_threshold( + skip_failures: bool, + transform: Option<&InputTransform>, + status_module: &FlowStatusModule, + module: &FlowModule, + flow_job: &MiniPulledJob, + status: &FlowStatus, + previous_id: &str, + last_result: Arc<Box<RawValue>>, + flow_args: Marc<HashMap<String, Box<RawValue>>>, + flow_env: Option<&HashMap<String, Box<RawValue>>>, + client: &AuthedClient, +) -> error::Result<Option<u32>> { + let Some(transform) = transform.filter(|_| skip_failures) else { + return Ok(None); + }; + if let FlowStatusModule::InProgress { + iterator: Some(FlowIterator { failure_threshold: Some(t), .. }), + .. + } = status_module + { + return Ok(Some(*t)); + } + let ctx = get_transform_context(flow_job, previous_id, status); + let threshold = evaluate_input_transform::<u32>( + transform, + last_result, + Some(flow_args), + flow_env, + Some(client), + Some(&ctx), + ) + .await?; + if threshold == 0 { + return Err(Error::BadRequest(format!( + "failure threshold of step {} must be at least 1", + module.id + ))); + } + Ok(Some(threshold)) +} + async fn compute_next_flow_transform( arc_flow_job_args: Marc<HashMap<String, Box<RawValue>>>, arc_last_job_result: Arc<Box<RawValue>>, @@ -6345,7 +6497,27 @@ async fn compute_next_flow_transform( NextStatus::NextStep, )) } - FlowModuleValue::WhileloopFlow { modules, modules_node, squash, .. } => { + FlowModuleValue::WhileloopFlow { + modules, + modules_node, + skip_failures, + failure_threshold, + .. + } => { + let failure_threshold = loop_failure_threshold( + skip_failures, + failure_threshold.as_ref(), + status_module, + module, + flow_job, + status, + previous_id, + arc_last_job_result, + arc_flow_job_args, + flow_env, + client, + ) + .await?; // if it's a simple single step flow, we will collapse it as an optimization and need to pass flow_input as an arg let is_simple = is_simple_modules(&modules, flow.failure_module.as_ref()); let (flow_jobs, flow_jobs_success, flow_jobs_duration) = match status_module { @@ -6363,7 +6535,7 @@ async fn compute_next_flow_transform( }; let next_loop_idx = flow_jobs.len(); - let start_runners = next_loop_idx == 0 && squash.unwrap_or(false); + let start_runners = false; next_loop_iteration( flow, status, @@ -6376,6 +6548,7 @@ async fn compute_next_flow_transform( flow_jobs_duration: flow_jobs_duration, flow_jobs_labels: None, iteration_label: None, + failure_threshold, new_args: Iter { index: next_loop_idx as i32, value: windmill_common::worker::to_raw_value(&next_loop_idx), @@ -6399,8 +6572,9 @@ async fn compute_next_flow_transform( modules_node, iterator, parallel, - squash, iteration_label, + skip_failures, + failure_threshold, .. } => { if failed_only.is_some() && !parallel { @@ -6424,6 +6598,7 @@ async fn compute_next_flow_transform( // } // _ => None, // } + let (last_result, flow_args) = (arc_last_job_result.clone(), arc_flow_job_args.clone()); // A failed-only restart reruns on the restarted run's items, never re-evaluating // the iterator, so each kept result stays paired with its item. let next_loop_status = if let Some(slots) = &failed_only { @@ -6455,13 +6630,35 @@ async fn compute_next_flow_transform( .await? }; + // Only once the loop has items: a percentage threshold of an empty list is 0. + let failure_threshold = if matches!(next_loop_status, ForLoopStatus::EmptyIterator) { + None + } else { + loop_failure_threshold( + skip_failures, + failure_threshold.as_ref(), + status_module, + module, + flow_job, + status, + previous_id, + last_result, + flow_args, + flow_env, + client, + ) + .await? + }; + match next_loop_status { ForLoopStatus::EmptyIterator => { Ok(NextFlowTransform::EmptyInnerFlows { branch_chosen: None }) } ForLoopStatus::NextIteration(mut ns) => { ns.iteration_label = iteration_label; - let start_runners = ns.index == 0 && squash.unwrap_or(false); + ns.failure_threshold = failure_threshold; + // A squashed loop runs each iteration as a regular job, like any other loop. + let start_runners = false; next_loop_iteration( flow, status, @@ -6529,6 +6726,7 @@ async fn compute_next_flow_transform( index: failed_only.as_ref().map_or(0, FailedOnlySlots::kept), itered_len: Some(itered_len), itered: Some(itered), + failure_threshold, }), iteration_label, // we removed the is_simple_case for simple_input_transforms @@ -7073,6 +7271,7 @@ async fn next_forloop_status( flow_jobs_duration: Some(FlowJobsDuration::new(0)), flow_jobs_labels: None, iteration_label: None, + failure_threshold: None, new_args: iter, while_loop: false, }) @@ -7150,6 +7349,7 @@ async fn next_forloop_status( flow_jobs_duration: flow_jobs_duration.clone(), flow_jobs_labels: flow_jobs_labels.clone(), iteration_label: None, + failure_threshold: None, new_args: Iter { index: index as i32, value: next.to_owned() }, while_loop: false, }) @@ -7574,6 +7774,7 @@ mod tests { approver: Some("ann".to_string()), approved: false, resume_id: 0, + created_at: chrono::Utc::now(), }; assert_eq!( denial(json!({"reason": " too risky "})).disapproval_error(), diff --git a/backend/windmill-worker/src/worker_lockfiles.rs b/backend/windmill-worker/src/worker_lockfiles.rs index 143cbb17e3..1dead293ea 100644 --- a/backend/windmill-worker/src/worker_lockfiles.rs +++ b/backend/windmill-worker/src/worker_lockfiles.rs @@ -1697,6 +1697,7 @@ async fn lock_modules( parallelism, squash, iteration_label, + failure_threshold, } => { let nmodules; (nmodules, nmodified_ids, nerrors) = Box::pin(lock_modules( @@ -1730,6 +1731,7 @@ async fn lock_modules( parallelism, squash, iteration_label, + failure_threshold, } .into() } @@ -1777,6 +1779,7 @@ async fn lock_modules( squash, max_iterations, max_duration_secs, + failure_threshold, } => { let nmodules; (nmodules, nmodified_ids, nerrors) = Box::pin(lock_modules( @@ -1808,6 +1811,7 @@ async fn lock_modules( squash, max_iterations, max_duration_secs, + failure_threshold, } .into() } diff --git a/backend/windmill-worker/src/worker_utils.rs b/backend/windmill-worker/src/worker_utils.rs index acfd6992d8..2f96e0054b 100644 --- a/backend/windmill-worker/src/worker_utils.rs +++ b/backend/windmill-worker/src/worker_utils.rs @@ -498,12 +498,13 @@ pub async fn get_tag_and_concurrency(job_id: &Uuid, db: &DB) -> Option<TagAndCon raw_flow->>'concurrency_time_window_s' as concurrency_time_window_s, raw_flow->>'concurrency_limit' as concurrent_limit, runnable_path, + workspace_id, runnable_id as version FROM v2_job WHERE id = $1 ) SELECT tag, j.concurrency_key, j.concurrency_time_window_s::int, j.concurrent_limit::int, j.version FROM flow, j - WHERE path = j.runnable_path + WHERE path = j.runnable_path AND flow.workspace_id = j.workspace_id ", job_id ) diff --git a/benchmarks/lib.ts b/benchmarks/lib.ts index e5a34f716e..07fca4ae69 100644 --- a/benchmarks/lib.ts +++ b/benchmarks/lib.ts @@ -2,7 +2,7 @@ import { sleep } from "https://deno.land/x/sleep@v1.2.1/mod.ts"; import * as windmill from "https://deno.land/x/windmill@v1.174.0/mod.ts"; import * as api from "https://deno.land/x/windmill@v1.174.0/windmill-api/index.ts"; -export const VERSION = "v1.884.1"; +export const VERSION = "v1.894.1"; export async function login(email: string, password: string): Promise<string> { return await windmill.UserService.login({ diff --git a/chat-sdk/package-lock.json b/chat-sdk/package-lock.json index 312cd3e5d0..515c97b7ed 100644 --- a/chat-sdk/package-lock.json +++ b/chat-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/chat-sdk", - "version": "1.884.1", + "version": "1.894.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/chat-sdk", - "version": "1.884.1", + "version": "1.894.1", "license": "Apache-2.0", "devDependencies": { "@ai-sdk/react": "^4.0.102", diff --git a/chat-sdk/package.json b/chat-sdk/package.json index ccb2d85ef5..298c3417e6 100644 --- a/chat-sdk/package.json +++ b/chat-sdk/package.json @@ -1,7 +1,7 @@ { "name": "@windmill-labs/chat-sdk", "description": "Build chat interfaces on Windmill flows deployed in chat mode, from any frontend or raw app", - "version": "1.884.1", + "version": "1.894.1", "author": "Ruben Fiszel", "license": "Apache-2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme", diff --git a/cli/src/commands/app/app.ts b/cli/src/commands/app/app.ts index b4d8230bdb..a8353d2316 100644 --- a/cli/src/commands/app/app.ts +++ b/cli/src/commands/app/app.ts @@ -102,12 +102,10 @@ export function replaceInlineScripts( const o: Record<string, any> = v as any; if (o["content"] && o["content"].startsWith("!inline")) { - const basePath = localPath + o["content"].split(" ")[1]; - o["content"] = readInlinePathSync(basePath); + o["content"] = readInlinePathSync(o["content"].split(" ")[1], localPath); } if (o["lock"] && o["lock"].startsWith("!inline")) { - const basePath = localPath + o["lock"].split(" ")[1]; - o["lock"] = readInlinePathSync(basePath); + o["lock"] = readInlinePathSync(o["lock"].split(" ")[1], localPath); } } else { replaceInlineScripts(v, localPath, addType); diff --git a/cli/src/commands/app/app_metadata.ts b/cli/src/commands/app/app_metadata.ts index 9513256d2d..f611efd392 100644 --- a/cli/src/commands/app/app_metadata.ts +++ b/cli/src/commands/app/app_metadata.ts @@ -23,7 +23,13 @@ import { ScriptLanguage, workspaceDependenciesLanguages, } from "../../utils/script_common.ts"; -import { generateHash, getHeaders, readTextFile, writeIfChanged } from "../../utils/utils.ts"; +import { + generateHash, + getHeaders, + inlinePathWithin, + readTextFile, + writeIfChanged, +} from "../../utils/utils.ts"; import { detectAuthGatewayChallenge } from "../../utils/http_guards.ts"; import { exts } from "../script/script.ts"; import { FSFSElement, yamlOptions, yamlSortedEntries } from "../sync/sync.ts"; @@ -227,9 +233,10 @@ export async function generateAppLocksInternal( let content = inlineScript.content; // Resolve !inline references if (typeof content === "string" && content.startsWith("!inline ")) { - const filePath = appFolder + SEP + content.replace("!inline ", ""); try { - content = await readTextFile(filePath); + content = await readTextFile( + inlinePathWithin(content.replace("!inline ", ""), appFolder), + ); } catch { return inlineScript; } diff --git a/cli/src/commands/app/bundle.ts b/cli/src/commands/app/bundle.ts index f99aba58a7..8f949a7d0a 100644 --- a/cli/src/commands/app/bundle.ts +++ b/cli/src/commands/app/bundle.ts @@ -22,6 +22,8 @@ export interface BundleOptions { * Allows raw apps to reuse components from the workspace-level shared folder. */ sharedUiDir?: string; + /** Run the dependencies' lifecycle scripts when installing them. */ + runInstallScripts?: boolean; } export interface BundleResult { @@ -268,28 +270,49 @@ export async function createFrameworkPlugins( /** * Ensures node_modules exists in the specified directory - * Runs npm install if node_modules is missing + * Runs npm install if node_modules is missing, without lifecycle scripts unless + * `runInstallScripts` is set: the app's package.json may come from a sync pull + * of someone else's app. * @param appDir Directory to check for node_modules (defaults to entry point directory) */ -export async function ensureNodeModules(appDir?: string): Promise<void> { +export async function ensureNodeModules( + appDir?: string, + runInstallScripts = false +): Promise<void> { const targetDir = appDir ?? process.cwd(); const nodeModulesPath = path.join(targetDir, "node_modules"); - if (!fs.existsSync(nodeModulesPath)) { - log.info(colors.yellow("📦 node_modules not found, running npm install...")); + const runNpm = async (args: string[]) => { const code = await new Promise<number>((resolve, reject) => { - const npmInstall = spawn("npm", ["install"], { + const npm = spawn("npm", args, { cwd: targetDir, stdio: "inherit", shell: true, }); - npmInstall.on("close", (code) => resolve(code ?? 0)); - npmInstall.on("error", reject); + npm.on("close", (code) => resolve(code ?? 0)); + npm.on("error", reject); }); if (code !== 0) { - throw new Error(`npm install failed with exit code ${code}`); + throw new Error(`npm ${args[0]} failed with exit code ${code}`); } + }; + + if (!fs.existsSync(nodeModulesPath)) { + const args = runInstallScripts ? ["install"] : ["install", "--ignore-scripts"]; + log.info( + colors.yellow(`📦 node_modules not found, running npm ${args.join(" ")}...`) + ); + await runNpm(args); log.info(colors.green("✅ npm install completed")); + if (!runInstallScripts) { + log.info( + `Lifecycle scripts were skipped. If a package needs its install script, run \`npm install\` in ${targetDir} first, or pass --run-install-scripts.` + ); + } + } else if (runInstallScripts) { + // node_modules may come from an earlier install that skipped them. + log.info(colors.yellow("📦 running npm rebuild to run install scripts...")); + await runNpm(["rebuild"]); } } @@ -399,7 +422,7 @@ export async function createBundle( } // Ensure node_modules exists in the app directory - await ensureNodeModules(appDir); + await ensureNodeModules(appDir, options.runInstallScripts); const sharedUiDir = options.sharedUiDir && fs.existsSync(options.sharedUiDir) diff --git a/cli/src/commands/app/bundle_command.ts b/cli/src/commands/app/bundle_command.ts index c4119aafb0..460a4a88d5 100644 --- a/cli/src/commands/app/bundle_command.ts +++ b/cli/src/commands/app/bundle_command.ts @@ -9,6 +9,7 @@ import { createBundle, detectFrameworks } from "./bundle.ts"; interface BundleOptions { out?: string; minify?: boolean; + runInstallScripts?: boolean; } /** Every entry point a raw app may have, most specific first, with the @@ -50,6 +51,7 @@ async function bundleApp(opts: BundleOptions, appFolder?: string) { // path against cwd — so name one that is ours to delete rather than let it // default to `dist`, which is very likely the caller's. outDir: `.wmill-bundle-${process.pid}`, + runInstallScripts: opts.runInstallScripts, }); const outDir = path.resolve(opts.out ?? path.join(appDir, "dist")); @@ -67,6 +69,10 @@ const command = new Command() "Directory to write bundle.js and bundle.css into (default: <app_folder>/dist)", ) .option("--no-minify", "Skip minification") + .option( + "--run-install-scripts", + "Run the dependencies' lifecycle scripts when installing node_modules", + ) .action(bundleApp as any); export default command; diff --git a/cli/src/commands/app/dev.ts b/cli/src/commands/app/dev.ts index 11fb5793bd..9e2e9d0ab4 100644 --- a/cli/src/commands/app/dev.ts +++ b/cli/src/commands/app/dev.ts @@ -50,6 +50,7 @@ import { hasFolderSuffix, loadNonDottedPathsSetting, } from "../../utils/resource_folders.ts"; +import { isAllowedHostHeader, isJobId } from "../../utils/dev_server_access.ts"; import { createRecorderShellHTML, DEV_RECORDER_BUNDLE, @@ -348,6 +349,7 @@ interface DevOptions extends GlobalOptions { entry?: string; open?: boolean; recording?: boolean; + runInstallScripts?: boolean; } async function dev(opts: DevOptions, appFolder?: string) { @@ -513,7 +515,7 @@ async function dev(opts: DevOptions, appFolder?: string) { // Ensure node_modules exists const appDir = path.dirname(entryPoint) || process.cwd(); - await ensureNodeModules(appDir); + await ensureNodeModules(appDir, opts.runInstallScripts); // In-memory cache of inferred schemas (runnableId -> schema) // Used to generate wmill.d.ts without modifying raw_app.yaml @@ -993,8 +995,28 @@ async function dev(opts: DevOptions, appFolder?: string) { res.end(createHTML("/dist/bundle.js", "/dist/bundle.css", appCtx)); }); - // Create WebSocket server on the same HTTP server - const wss = new WebSocketServer({ server }); + // Its messages run runnables, SQL and API calls with the CLI's token, and a + // browser lets a page of any origin open `ws://localhost:<port>`: only the + // page this server serves, reached under a name DNS cannot re-point, may + // upgrade. + const wss = new WebSocketServer({ + server, + verifyClient: (info: { req: http.IncomingMessage }) => { + const { origin, host: hostHeader } = info.req.headers; + if ( + isOwnOrigin(origin, hostHeader) && + isAllowedHostHeader(hostHeader, host) + ) { + return true; + } + log.warn( + colors.yellow( + `[WebSocket] Refused connection from origin ${JSON.stringify(origin)} (host ${JSON.stringify(hostHeader)}). Open http://localhost:${port}, or start with --host <name> to accept that name.`, + ), + ); + return false; + }, + }); // SQL migration state (defined here so it's accessible in WebSocket handler) const sqlToApplyPath = path.join(process.cwd(), "sql_to_apply"); @@ -1202,6 +1224,18 @@ async function dev(opts: DevOptions, appFolder?: string) { return { uuid, result }; }; + if ( + (type === "waitJob" || type === "getJob" || type === "streamJob") && + !isJobId(jobId) + ) { + respond( + type === "streamJob" ? "streamJobRes" : "backendRes", + { message: `Invalid job id: ${JSON.stringify(jobId)}` }, + true, + ); + return; + } + switch (type) { case "backend": { // Run a runnable synchronously and wait for result @@ -1634,6 +1668,10 @@ const command = new Command() "Entry point file (default: index.ts for Svelte, index.tsx otherwise)", ) .option("--no-open", "Don't automatically open the browser") + .option( + "--run-install-scripts", + "Run the dependencies' lifecycle scripts when installing node_modules", + ) .option( "--recording", "Frame the app in a shell with a Record button, to capture a replayable session recording of the app under development", diff --git a/cli/src/commands/dev/dev.ts b/cli/src/commands/dev/dev.ts index 562c38233e..0769f57b17 100644 --- a/cli/src/commands/dev/dev.ts +++ b/cli/src/commands/dev/dev.ts @@ -9,7 +9,7 @@ import * as http from "node:http"; import * as https from "node:https"; import * as open from "open"; import { access, readdir, realpath, stat, unlink, writeFile } from "node:fs/promises"; -import { readTextFile } from "../../utils/utils.ts"; +import { inlinePathWithin, readTextFile } from "../../utils/utils.ts"; import { watch } from "node:fs"; import { getTypeStrFromPath, GlobalOptions } from "../../types.ts"; import { ignoreF } from "../sync/sync.ts"; @@ -51,6 +51,12 @@ import * as fs from "node:fs"; import { listSyncCodebases } from "../../utils/codebase.ts"; import { createPreviewLocalScriptReader } from "../../utils/local_path_scripts.ts"; import { resolveBindPort, BIND_HOST } from "../../utils/port-probe.ts"; +import { + bindsLocalhost, + isAllowedDevPageOrigin, + isAllowedHostHeader, + isWithinFolder, +} from "../../utils/dev_server_access.ts"; import { snapshotPathScripts, tagReplacedPathScripts, @@ -212,6 +218,7 @@ export interface DevOpts { proxyPort?: number; path?: string; open?: boolean; + host?: string; } export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { @@ -266,6 +273,32 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { const ignore = await ignoreF(opts); const codebases = await listSyncCodebases(opts); + // Paths the dev socket reads and writes come from its client: a message + // names a file, and a flow.yaml (which a message can rewrite) names its + // `!inline` files and the scripts it calls. None may resolve outside the + // checkout. Relative paths resolve against the cwd, which can spell the + // checkout differently from its realpath (a Windows 8.3 short name such as + // `RUNNER~1`, a symlinked parent), so either spelling counts as inside. + const cwd = process.cwd(); + const isInCheckout = (p: string) => + isWithinFolder(base, p) || isWithinFolder(cwd, p); + function inCheckout(p: string): string { + if (!isInCheckout(p)) { + throw new Error(`${p} is outside of ${base}`); + } + return p; + } + const createLocalScriptReader = () => { + const read = createPreviewLocalScriptReader({ + exts, + defaultTs: opts.defaultTs, + codebases, + }); + // Outside the checkout is not a local script: the deployed one is used. + return (p: string) => + isInCheckout(p) ? read(p) : Promise.resolve(undefined); + }; + // Resolve relative imports from local (not-yet-deployed) content so dev-page // previews use locally-edited workspace scripts instead of the deployed // versions. Diverged local scripts are uploaded to temp storage once here @@ -325,6 +358,7 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { const rest: string[] = []; const scriptsWithModules = new Set<string>(); for (const raw of pathsToLoad) { + inCheckout(raw); const rel = (await realpath(raw).catch(() => raw)) .replace(base + SEP, "") .replaceAll("\\", "/"); @@ -380,7 +414,8 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { )) as FlowFile; await replaceInlineScripts( localFlow.value.modules, - async (path: string) => await readTextFile(localPath + path), + async (path: string) => + await readTextFile(inlinePathWithin(path, localPath)), log, localPath, SEP, @@ -390,12 +425,7 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { // Helpers walk `flowValue` (modules/failure_module/preprocessor_module), // so pass `.value`, not the FlowFile wrapper. snapshotPathScripts(localFlow.value); - const localScriptReader = createPreviewLocalScriptReader({ - exts, - defaultTs: opts.defaultTs, - codebases, - }); - await replaceAllPathScriptsWithLocal(localFlow.value, localScriptReader, log); + await replaceAllPathScriptsWithLocal(localFlow.value, createLocalScriptReader(), log); tagReplacedPathScripts(localFlow.value); currentLastEdit = { type: "flow", @@ -457,7 +487,7 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { // Load a resource by its windmill path (e.g., "u/admin/my_script" or "f/my_flow") async function loadWmPath(wmPath: string): Promise<LastEditScript | LastEditFlow | undefined> { - wmPath = normalizeWmPath(wmPath); + wmPath = inCheckout(normalizeWmPath(wmPath)); // Try as flow — check both dotted and non-dotted suffixes let flowDir: string | undefined; let flowYaml: string | undefined; @@ -475,19 +505,14 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { const localFlow = (await yamlParseFile(flowYaml)) as FlowFile; await replaceInlineScripts( localFlow.value.modules, - async (p: string) => await readTextFile(flowDir + p), + async (p: string) => await readTextFile(inlinePathWithin(p, flowDir)), log, flowDir, SEP, undefined, ); snapshotPathScripts(localFlow.value); - const localScriptReader = createPreviewLocalScriptReader({ - exts, - defaultTs: opts.defaultTs, - codebases, - }); - await replaceAllPathScriptsWithLocal(localFlow.value, localScriptReader, log); + await replaceAllPathScriptsWithLocal(localFlow.value, createLocalScriptReader(), log); tagReplacedPathScripts(localFlow.value); const edit: LastEditFlow = { type: "flow", @@ -577,6 +602,10 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { if (flowDir.includes("://")) { flowDir = new URL(flowDir).pathname; } + inCheckout(flowDir); + if (!isFlowFolderName(path.basename(flowDir))) { + throw new Error(`${flowDir} is not a flow folder`); + } // Restore PathScripts BEFORE extracting so we don't write a file for the // inlined body of a `type: 'script'` reference. @@ -637,6 +666,12 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { )); } + // Checked before any write, so a refused edit leaves the folder untouched. + for (const s of allExtracted) { + if (!isWithinFolder(flowDir, flowDir + s.path)) { + throw new Error(`${s.path} is outside of ${flowDir}`); + } + } for (const s of allExtracted) { const filePath = flowDir + s.path; // `!inline foo.ts` is a YAML directive that points at another file — @@ -697,6 +732,32 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { const connectedClients: Set<WebSocket> = new Set(); + const bindHost = opts.host ?? BIND_HOST; + if (!bindsLocalhost(bindHost)) { + throw new Error( + `--host ${bindHost}: the dev page connects to localhost, so bind to a loopback address or to 0.0.0.0 (every interface)` + ); + } + + // The socket ships the checkout's sources and writes flow edits back to + // disk, and any browser tab can open `ws://localhost:<port>`. The dev page + // is served by the workspace remote (or, with --proxy-port, by this + // machine), and a page cannot forge the Origin it states. + function verifyDevClient(info: { req: http.IncomingMessage }): boolean { + const { origin, host } = info.req.headers; + if ( + isAllowedDevPageOrigin(origin, workspace.remote) && + isAllowedHostHeader(host, bindHost) + ) { + return true; + } + log.warn( + `Refused a dev WebSocket connection from origin ${JSON.stringify(origin)} (host ${JSON.stringify(host)}): ` + + `the dev page is served from ${new URL(workspace.remote).origin} or localhost` + ); + return false; + } + // Send a message to all connected clients, gated by --path when set so we // don't spam clients (or risk yanking their view) with edits to unrelated files. function broadcastChanges(lastEdit: LastEditScript | LastEditFlow) { @@ -752,7 +813,9 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { } if (data.type === "load") { - loadPaths([data.path]); + loadPaths([data.path]).catch((err) => { + log.error(`Failed to load ${data.path}: ${err}`); + }); } else if (data.type === "flow") { pendingFlowMessage = data; if (flowDebounceTimer) { @@ -833,12 +896,19 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { const remotePort = remote.port ? parseInt(remote.port) : (isHttps ? 443 : 80); const httpModule = isHttps ? https : http; - const devWss = new WebSocketServer({ noServer: true }); + const devWss = new WebSocketServer({ noServer: true, verifyClient: verifyDevClient }); setupDevWs(devWss); const proxyWss = new WebSocketServer({ noServer: true }); const proxyServer = http.createServer((clientReq, clientRes) => { + // `/` hands out the workspace token: refuse a name DNS could have + // re-pointed at this machine. + if (!isAllowedHostHeader(clientReq.headers.host, bindHost)) { + clientRes.writeHead(403); + clientRes.end("Forbidden host"); + return; + } const parsedUrl = new URL(clientReq.url ?? "/", `http://localhost`); if (parsedUrl.pathname === "/" || parsedUrl.pathname === "") { let devUrl = `/dev?workspace=${workspace.workspaceId}&local=true&wm_token=${workspace.token}&port=${proxyPort}`; @@ -889,6 +959,10 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { // WebSocket upgrades proxyServer.on("upgrade", (req, socket, head) => { + if (!isAllowedHostHeader(req.headers.host, bindHost)) { + socket.destroy(); + return; + } const pathname = req.url?.split("?")[0] ?? ""; if (pathname === "/ws_dev" || pathname === "/ws") { @@ -936,7 +1010,7 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { }); return new Promise<void>((resolve) => { - proxyServer.listen(proxyPort, BIND_HOST, () => { + proxyServer.listen(proxyPort, bindHost, () => { console.log(`Dev proxy listening on http://localhost:${proxyPort}`); if (opts.path) { console.log(`Watching ${opts.path} — edits will live-reload in the dev page`); @@ -970,7 +1044,7 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { res.writeHead(200); res.end(); }); - const wss = new WebSocketServer({ server }); + const wss = new WebSocketServer({ server, verifyClient: verifyDevClient }); setupDevWs(wss); // Probe both IPv4 and IPv6 stacks before binding. Same dual-stack @@ -999,7 +1073,7 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { ); } - server.listen(port, BIND_HOST, () => { + server.listen(port, bindHost, () => { console.log(`Dev WebSocket listening on ws://localhost:${port}/ws`); }); } @@ -1037,6 +1111,10 @@ const command = new Command() "--no-open", "Do not open the browser automatically" ) + .option( + "--host <host:string>", + "Address to bind the dev server to: a loopback address or 0.0.0.0 for every interface (default: 127.0.0.1, this machine only)" + ) .action(dev as any); export default command; diff --git a/cli/src/commands/flow/flow.ts b/cli/src/commands/flow/flow.ts index 94944d3f06..8d419e38f0 100644 --- a/cli/src/commands/flow/flow.ts +++ b/cli/src/commands/flow/flow.ts @@ -8,7 +8,11 @@ import { ciTestBatchDeployed, ciTestBatchSkip } from "../../core/ci_test_batch.t import { dirname, sep as SEP, resolve as pathResolve } from "node:path"; import { stringify as yamlStringify } from "yaml"; import { yamlParseFile } from "../../utils/yaml.ts"; -import { readTextFile, validateRequiredArgs } from "../../utils/utils.ts"; +import { + inlinePathWithin, + readTextFile, + validateRequiredArgs, +} from "../../utils/utils.ts"; import * as wmill from "../../../gen/services.gen.ts"; import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs"; import { buildFolderPath, getMetadataFileName, loadNonDottedPathsSetting } from "../../utils/resource_folders.ts"; @@ -181,7 +185,8 @@ export async function readLocalFlow( } const localFlow = (await yamlParseFile(localPath + "flow.yaml")) as FlowFile; - const fileReader = async (path: string) => await readTextFile(localPath + path); + const fileReader = async (path: string) => + await readTextFile(inlinePathWithin(path, localPath)); const missingFiles: string[] = []; await replaceInlineScripts( localFlow.value.modules, @@ -683,7 +688,8 @@ async function preview( const localFlow = (await yamlParseFile(flowPath + "flow.yaml")) as FlowFile; // Replace inline scripts with their actual content - const fileReader = async (path: string) => await readTextFile(flowPath + path); + const fileReader = async (path: string) => + await readTextFile(inlinePathWithin(path, flowPath)); await replaceInlineScripts( localFlow.value.modules, fileReader, diff --git a/cli/src/commands/flow/flow_metadata.ts b/cli/src/commands/flow/flow_metadata.ts index 180491ea90..03a5c2c659 100644 --- a/cli/src/commands/flow/flow_metadata.ts +++ b/cli/src/commands/flow/flow_metadata.ts @@ -22,7 +22,13 @@ import { ScriptLanguage } from "../../utils/script_common.ts"; import { extractInlineScripts as extractInlineScriptsForFlows, extractCurrentMapping, legacyLockPathForContent } from "../../../windmill-utils-internal/src/inline-scripts/extractor.ts"; import { newPathAssigner } from "../../../windmill-utils-internal/src/path-utils/path-assigner.ts"; -import { generateHash, getHeaders, readTextFile, writeIfChanged } from "../../utils/utils.ts"; +import { + generateHash, + getHeaders, + inlinePathWithin, + readTextFile, + writeIfChanged, +} from "../../utils/utils.ts"; import { detectAuthGatewayChallenge } from "../../utils/http_guards.ts"; import { exts } from "../script/script.ts"; import { FSFSElement, yamlOptions } from "../sync/sync.ts"; @@ -246,7 +252,8 @@ export async function generateFlowLockInternal( if (!noStaleMessage) { log.info(`Recomputing locks of ${changedScripts.join(", ")} in ${folder}`); } - const fileReader = async (path: string) => await readTextFile(folder + SEP + path); + const fileReader = async (path: string) => + await readTextFile(inlinePathWithin(path, folder)); // Capture existing module-ID-to-file-path mapping before replaceInlineScripts // overwrites the !inline references with actual file content. This preserves diff --git a/cli/src/commands/generate-metadata/generate-metadata.ts b/cli/src/commands/generate-metadata/generate-metadata.ts index 7310efc483..1e2d73834d 100644 --- a/cli/src/commands/generate-metadata/generate-metadata.ts +++ b/cli/src/commands/generate-metadata/generate-metadata.ts @@ -1,7 +1,8 @@ import { Command } from "@cliffy/command"; import { Confirm } from "@cliffy/prompt/confirm"; import { colors } from "@cliffy/ansi/colors"; -import { sep as SEP } from "node:path"; +import { readdir, stat } from "node:fs/promises"; +import { join, sep as SEP } from "node:path"; import { GlobalOptions, isDatatableMigrationPath } from "../../types.ts"; import { isFileResource, isFilesetResource } from "../../utils/utils.ts"; import { SyncOptions, mergeConfigWithConfigFile } from "../../core/conf.ts"; @@ -412,6 +413,29 @@ export async function rehashOnly( return counts; } +/** + * Whether `target` (a file, or any file under a folder) is dropped by the + * includes/excludes alone: `ignore` also drops every file that is not a + * Windmill item, which `unfiltered` (built without those rules) drops too. + */ +async function isFilteredByIncludes( + target: string, + ignore: (p: string, isD: boolean) => boolean, + unfiltered: (p: string, isD: boolean) => boolean, +): Promise<boolean> { + const native = target.replaceAll("/", SEP); + const filtered = (p: string) => ignore(p, false) && !unfiltered(p, false); + let info; + try { + info = await stat(native); + } catch { + return false; + } + if (!info.isDirectory()) return filtered(native); + const entries = await readdir(native, { recursive: true, withFileTypes: true }); + return entries.some((e) => e.isFile() && filtered(join(e.parentPath, e.name))); +} + /** * Normalize the tree's shared lockfiles, unless the run asked to stay inside one * folder: shared lockfiles are workspace-wide, so the pass reads and rewrites @@ -473,6 +497,18 @@ export async function generateMetadata( if (folder === "") { folder = undefined; } + // Normalize to forward slashes (Windows users may use backslashes) and strip + // a trailing slash to match deprecated flow/app handler behavior + folder = folder?.replaceAll("\\", "/").replace(/\/$/, ""); + // Strip file extension if user passed a specific file path (e.g. f/test/script.ts) + const folderNoExt = folder?.replace(/\.[^/.]+$/, ""); + const isPathInFolder = (p: string) => + folder !== undefined && + (p.startsWith(folder + "/") || p === folder || p === folderNoExt); + let walkedInFolder = false; + const noteWalked = (p: string) => { + if (isPathInFolder(p.replaceAll("\\", "/"))) walkedInFolder = true; + }; const workspace = await resolveWorkspace(opts); await requireLogin(opts); @@ -506,6 +542,10 @@ export async function generateMetadata( // === Collect stale scripts === if (!skipScripts) { for (const e of await walkLocalScripts(codebases, ignore)) { + // A file target (`f/x/task.deno.ts`, `f/x/task__mod/script.ts`) matches the + // local path, a folder target the remote one. + noteWalked(e); + noteWalked(scriptPathToRemotePath(e)); await generateScriptMetadataInternal( e, workspace, @@ -523,6 +563,7 @@ export async function generateMetadata( // === Collect stale flows === if (!skipFlows) { for (const flowFolder of await walkLocalFlowFolders(ignore)) { + noteWalked(flowFolder); await generateFlowLockInternal( flowFolder, true, // dryRun - populate tree @@ -538,6 +579,7 @@ export async function generateMetadata( // === Collect stale apps === if (!skipApps) { for (const { folder: appFolder, rawApp } of await walkLocalAppItems(ignore)) { + noteWalked(appFolder); await generateAppLocksInternal( appFolder, rawApp, @@ -551,6 +593,27 @@ export async function generateMetadata( } } + // Tree nodes also cover workspace dependency files, which the walk never lists. + if (folder && !walkedInFolder && ![...tree.allPaths()].some(isPathInFolder)) { + const unfiltered = await ignoreF({ + ...opts, includes: undefined, excludes: undefined, extraIncludes: undefined, + }); + if (await isFilteredByIncludes(folder, ignore, unfiltered)) { + const pattern = (await stat(folder.replaceAll("/", SEP))).isDirectory() + ? `${folder}/**` + : folder; + log.warn(colors.yellow( + `Nothing under "${folder}" was checked: the includes/excludes in effect (wmill.yaml or -i/-e) filter it out. ` + + `Pass --includes "${pattern}" to check it, after removing any excludes that match it.` + )); + } else { + log.warn(colors.yellow(`No scripts, flows or apps to check under "${folder}".`)); + } + // Same reason as the up-to-date path below: the conversion still applies. + await maybeDedupeLockfiles(opts, workspace, codebases, ignore, rawWorkspaceDependencies, tree, folder); + return; + } + // === Propagate staleness through imports === tree.propagateStaleness(); @@ -597,14 +660,6 @@ export async function generateMetadata( // === Filter by folder if specified === let filteredItems = staleItems; if (folder) { - // Normalize to forward slashes (Windows users may use backslashes) - folder = folder.replaceAll("\\", "/"); - // Strip trailing slash to match deprecated flow/app handler behavior - if (folder.endsWith("/")) { - folder = folder.substring(0, folder.length - 1); - } - // Strip file extension if user passed a specific file path (e.g. f/test/script.ts) - const folderNoExt = folder.replace(/\.[^/.]+$/, ""); // Check if an item is inside the specified folder const isInsideFolder = (item: StaleItem) => { const normalizedFolder = item.folder.replaceAll("\\", "/"); @@ -612,7 +667,6 @@ export async function generateMetadata( return normalizedFolder === folder || normalizedFolder.startsWith(folder + "/") || normalizedPath === folder || normalizedPath === folderNoExt; }; - const isPathInFolder = (p: string) => p.startsWith(folder + "/") || p === folder || p === folderNoExt; // Check if a tree path or any of its transitive deps is inside the folder const touchesFolder = (treePath: string) => { if (isPathInFolder(treePath)) return true; diff --git a/cli/src/commands/hub/hub.ts b/cli/src/commands/hub/hub.ts index 1a9c89680e..512be85421 100644 --- a/cli/src/commands/hub/hub.ts +++ b/cli/src/commands/hub/hub.ts @@ -54,6 +54,7 @@ export async function pull(opts: GlobalOptions) { if (hubBaseUrl !== DEFAULT_HUB_BASE_URL) { const hubSecret = (await wmill.getGlobal({ key: "hub_api_secret", + dangerouslyRevealSecrets: true, })) as string | undefined; log.info("Fetching resource types from private hub: " + hubBaseUrl); if (hubSecret) { diff --git a/cli/src/commands/instance/instance.ts b/cli/src/commands/instance/instance.ts index f2285a5316..ba1ce12e98 100644 --- a/cli/src/commands/instance/instance.ts +++ b/cli/src/commands/instance/instance.ts @@ -38,6 +38,7 @@ import { pullInstanceSettings, pushInstanceConfigs, pushInstanceSettings, + REDACTED_SECRET_PREFIX, type SimplifiedSettings, } from "../../core/settings.ts"; import { deepEqual, readTextFile } from "../../utils/utils.ts"; @@ -183,6 +184,7 @@ export type InstanceSyncOptions = { yes?: boolean; prefix?: string; prefixSettings?: boolean; + showSecrets?: boolean; }; export async function pickInstance( @@ -667,25 +669,42 @@ export async function getActiveInstance(opts: { async function getConfig(opts: InstanceSyncOptions & { outputFile?: string; showSecrets?: boolean }) { await pickInstance(opts, false); - const config = await wmill.getInstanceConfig() as any; - - // In interactive mode, mask secrets by default and prompt - const hasSecrets = config?.global_settings?.license_key || config?.global_settings?.jwt_secret; let showSecrets = opts.showSecrets ?? false; - if (!showSecrets && hasSecrets && process.stdout.isTTY && !opts.outputFile) { - log.warn("Config contains sensitive fields (license_key, jwt_secret). They are masked by default."); - log.warn("Use --show-secrets to include them, or press Y to show them now."); - showSecrets = await Confirm.prompt({ message: "Show secrets?", default: false }); - } else if (!process.stdout.isTTY || opts.outputFile) { - // Non-interactive or writing to file: always include secrets - showSecrets = true; - } + let config = await wmill.getInstanceConfig({ dangerouslyRevealSecrets: showSecrets }) as any; - if (!showSecrets && config?.global_settings) { + const settings = config?.global_settings ?? {}; + const serverRedacted = JSON.stringify(settings).includes(REDACTED_SECRET_PREFIX); + // A server without redaction ignores the parameter and returns its secrets in clear. + const clearFromOlderServer = + !showSecrets && !serverRedacted && Boolean(settings.license_key || settings.jwt_secret); + const interactive = process.stdout.isTTY && !opts.outputFile; + // Masking such an export is only safe on screen: applied back, that server would store the mask. + if (clearFromOlderServer && !interactive) { + throw new Error( + "This server does not redact secrets, so a redacted export would overwrite them when applied back. Pass --show-secrets to export them." + ); + } + const redacted = !showSecrets && (serverRedacted || clearFromOlderServer); + if (redacted && interactive) { + log.warn( + clearFromOlderServer + ? "Config contains sensitive fields (license_key, jwt_secret). They are masked by default. Use --show-secrets to include them, or press Y to show them now." + : "Secrets (license key, passwords, tokens) are redacted. Use --show-secrets to include them, or press Y to show them now." + ); + showSecrets = await Confirm.prompt({ message: "Show secrets?", default: false }); + if (showSecrets) { + config = await wmill.getInstanceConfig({ dangerouslyRevealSecrets: true }) as any; + } + } else if (redacted) { + log.infoStderr( + "Secrets are redacted: pass --show-secrets to include them. Pushing this export back keeps the stored secrets, but it cannot set up another instance." + ); + } + if (!showSecrets && clearFromOlderServer) { if (config.global_settings.license_key) config.global_settings.license_key = "***"; if (config.global_settings.jwt_secret) config.global_settings.jwt_secret = "***"; } - if (config?.global_settings && !config.global_settings.jwt_secret) { + if (showSecrets && config?.global_settings && !config.global_settings.jwt_secret) { log.infoStderr( "jwt_secret, rsa_keys and the instance database secrets are not part of the export: the server withholds them (EXPORT_SERVER_SECRETS=false). This export cannot fully restore or migrate the instance." ); @@ -778,6 +797,10 @@ const command = new Command() .option("--dry-run", "Perform a dry run without making changes") .option("--skip-users", "Skip pulling users") .option("--skip-settings", "Skip pulling settings") + .option( + "--show-secrets", + "Pull secrets (license key, passwords, tokens) in clear instead of redacted", + ) .option("--skip-configs", "Skip pulling configs (worker groups)") .option("--skip-groups", "Skip pulling instance groups") .option("--include-workspaces", "Also pull workspaces") @@ -826,7 +849,7 @@ const command = new Command() .command("get-config") .description("Dump the current instance config (global settings + worker configs) as YAML") .option("-o, --output-file <file:string>", "Write YAML to a file instead of stdout") - .option("--show-secrets", "Include sensitive fields (license key, JWT secret) without prompting") + .option("--show-secrets", "Include secrets (license key, passwords, tokens) in clear without prompting") .option( "--instance <instance:string>", "Name of the instance, override the active instance", diff --git a/cli/src/commands/resource/resource.ts b/cli/src/commands/resource/resource.ts index 4470daa276..80a10902de 100644 --- a/cli/src/commands/resource/resource.ts +++ b/cli/src/commands/resource/resource.ts @@ -18,7 +18,11 @@ import { ciTestBatchDeployed, ciTestBatchSkip } from "../../core/ci_test_batch.t import { sep as SEP } from "node:path"; import * as wmill from "../../../gen/services.gen.ts"; import { Resource } from "../../../gen/types.gen.ts"; -import { readInlinePathSync, readTextFile } from "../../utils/utils.ts"; +import { + inlinePathWithin, + readInlinePathSync, + readTextFile, +} from "../../utils/utils.ts"; import { isWorkspaceSpecificFile } from "../../core/specific_items.ts"; import { getCurrentGitBranch } from "../../utils/git.ts"; import { @@ -78,6 +82,38 @@ export function validateFilesetPointer( } } +/** + * A synced resource's `!inline` content pointer must name its own + * `<resource path>.resource.file.<ext>`, the only file a pull writes for it. + * The pointer is pulled verbatim from the stored value, so any other target + * would read an unrelated local file into the pushed resource. + */ +export function validateInlineResourcePointer( + ref: string, + remotePath: string, + localPath?: string, +): void { + const normalize = (p: string) => p.replaceAll("\\", "/"); + const pointer = normalize(ref); + const bases = [normalize(remotePath.replaceAll(SEP, "/"))]; + if (localPath) { + bases.push(normalize(localPath).replace(/\.resource\.(ya?ml|json)$/, "")); + } + const ok = bases.some((base) => { + const prefix = base + ".resource.file."; + const ext = pointer.slice(prefix.length); + return pointer.startsWith(prefix) && ext !== "" && !ext.includes("/"); + }); + if (!ok) { + const expected = bases[0] + ".resource.file.<ext>"; + throw new Error( + `Resource ${bases[0]} uses '!inline ${ref}', but a resource's content ` + + `file must live next to it, at '${expected}'. Move the file there and ` + + `update the '!inline' value to match.`, + ); + } +} + export async function pushResource( workspace: string, remotePath: string, @@ -85,10 +121,11 @@ export async function pushResource( localResource: ResourceFile, originalLocalPath?: string, wsSpecific?: boolean, - // Sync pushes reject non-canonical fileset pointers (the diff engine can - // only round-trip the canonical layout); the standalone `resource push` - // command pushes a single explicit file, where any pointer is fine. - enforceCanonicalFileset?: boolean, + // Sync pushes reject non-canonical fileset and content-file pointers (the + // diff engine can only round-trip the canonical layout, and the pointer is + // pulled data); the standalone `resource push` command pushes a single + // explicit file, where any pointer inside the current directory is fine. + enforceCanonicalPointers?: boolean, permissionedAsContext?: PermissionedAsContext, ): Promise<void> { remotePath = removeType(remotePath, "resource"); @@ -110,12 +147,15 @@ export async function pushResource( const resolveInlineContent = async () => { if (typeof localResource.value === "string" && localResource.value.startsWith("!inline_fileset ")) { const dirPath = localResource.value.split(" ")[1]; - if (enforceCanonicalFileset) { + if (enforceCanonicalPointers) { validateFilesetPointer(dirPath, remotePath); } - localResource.value = await readFilesetDirectory(dirPath.replaceAll("/", SEP)); + localResource.value = await readFilesetDirectory(inlinePathWithin(dirPath)); } else if (localResource.value["content"]?.startsWith("!inline ")) { const basePath = localResource.value["content"].split(" ")[1]; + if (enforceCanonicalPointers) { + validateInlineResourcePointer(basePath, remotePath, originalLocalPath); + } // If we're processing a branch-specific metadata file, read from branch-specific resource file diff --git a/cli/src/commands/script/script.ts b/cli/src/commands/script/script.ts index 28f7ab588c..bd3dd588f4 100644 --- a/cli/src/commands/script/script.ts +++ b/cli/src/commands/script/script.ts @@ -845,6 +845,19 @@ export async function readModulesFromDisk( const relPath = relPrefix ? relPrefix + "/" + entry.name : entry.name; const isTopLevel = relPrefix === ""; + // A resource whose path lies under the project's folder is written there by a + // pull, but it is its own item, possibly someone else's: not a project file. + if ( + verbatim && + (entry.isDirectory() + ? entry.name.endsWith(".fileset") + : isFileResource(entry.name) || /\.resource\.(json|ya?ml)$/.test(entry.name)) + ) { + log.warn( + `Skipping ${relPath}: a resource stored under the dbt project's folder is not part of the project`, + ); + continue; + } if (entry.isDirectory()) { // A configured `target-path` may be nested (`build/target`), so the // comparison is on the project-relative path, not the entry name. diff --git a/cli/src/commands/sync/sync.ts b/cli/src/commands/sync/sync.ts index 63521289c8..ec5e7a6615 100644 --- a/cli/src/commands/sync/sync.ts +++ b/cli/src/commands/sync/sync.ts @@ -1169,6 +1169,30 @@ export function rawAppPathWithinFolder( return resolved; } +/** + * Join a fileset key or script module name under `baseFolder`. Both are remote + * data written to disk on pull and read back with `/` joins on push, so only a + * plain relative `/`-separated path round-trips; anything else is refused. + */ +export function remoteKeyWithinFolder( + baseFolder: string, + key: string, +): string { + const segments = key.split("/"); + if ( + key.includes("\0") || + key.includes("\\") || + key.startsWith("/") || + /^[A-Za-z]:/.test(key) || + segments.some((s) => s === "" || s === "." || s === "..") + ) { + throw new Error( + `path ${JSON.stringify(key)} must be a relative path inside ${baseFolder}`, + ); + } + return rawAppPathWithinFolder(baseFolder, key); +} + export function ZipFSElement( zip: JSZip, useYaml: boolean, @@ -1819,7 +1843,7 @@ export function ZipFSElement( // Yield the module content file yield { isDirectory: false, - path: path.join(moduleFolderPath, relPath), + path: remoteKeyWithinFolder(moduleFolderPath, relPath), async *getChildren() {}, async getContentText() { return mod.content; @@ -1831,7 +1855,10 @@ export function ZipFSElement( const baseName = relPath.replace(/\.[^.]+$/, ""); yield { isDirectory: false, - path: path.join(moduleFolderPath, baseName + ".lock"), + path: remoteKeyWithinFolder( + moduleFolderPath, + baseName + ".lock", + ), async *getChildren() {}, async getContentText() { return mod.lock!; @@ -1877,7 +1904,7 @@ export function ZipFSElement( if (typeof fileContent === "string") { yield { isDirectory: false, - path: path.join(filesetBasePath, relPath), + path: remoteKeyWithinFolder(filesetBasePath, relPath), async *getChildren() {}, async getContentText() { return fileContent; diff --git a/cli/src/commands/token/token.ts b/cli/src/commands/token/token.ts index d0c8cda76d..f0f5204627 100644 --- a/cli/src/commands/token/token.ts +++ b/cli/src/commands/token/token.ts @@ -5,9 +5,16 @@ import { Table } from "@cliffy/table"; import { colors } from "@cliffy/ansi/colors"; import * as log from "../../core/log.ts"; import { mergeConfigWithConfigFile } from "../../core/conf.ts"; +import { resolveWorkspace } from "../../core/context.ts"; import * as wmill from "../../../gen/services.gen.ts"; +import type { TruncatedToken } from "../../../gen/types.gen.ts"; import { formatTimestamp } from "../../utils/utils.ts"; +function access(t: TruncatedToken): string { + const level = t.super_admin ? "superadmin" : t.admin ? "admin" : "member"; + return t.read_only ? `${level}, read-only` : level; +} + async function list(opts: GlobalOptions & { json?: boolean }) { if (opts.json) log.setSilent(true); opts = await mergeConfigWithConfigFile(opts); @@ -25,7 +32,7 @@ async function list(opts: GlobalOptions & { json?: boolean }) { return; } new Table() - .header(["Prefix", "Label", "Created At", "Last Used", "Expiration"]) + .header(["Prefix", "Label", "Created At", "Last Used", "Expiration", "Workspace", "Access", "Scopes"]) .padding(2) .border(true) .body( @@ -35,6 +42,9 @@ async function list(opts: GlobalOptions & { json?: boolean }) { formatTimestamp(t.created_at), formatTimestamp(t.last_used_at), t.expiration ? formatTimestamp(t.expiration) : "never", + t.workspace_id ?? "all", + access(t), + t.scopes && t.scopes.length > 0 ? t.scopes.join(" ") : "unscoped", ]) ) .render(); @@ -45,21 +55,67 @@ async function create( opts: GlobalOptions & { label?: string; expiration?: string; + allWorkspaces?: boolean; + admin?: boolean; + superadmin?: boolean; + scope?: string[]; } ) { opts = await mergeConfigWithConfigFile(opts); await requireLogin(opts); + // Bound to the current workspace unless asked otherwise: a bound token is refused on every + // other workspace and on instance-level endpoints. + const workspaceId = opts.allWorkspaces + ? undefined + : (await resolveWorkspace(opts)).workspaceId; + if (opts.superadmin && workspaceId) { + log.warn( + "The token is bound to workspace " + + workspaceId + + ": instance-level endpoints will refuse it. Pass --all-workspaces for instance commands." + ); + } + const token = await wmill.createToken({ requestBody: { label: opts.label, expiration: opts.expiration, + workspace_id: workspaceId, + admin: opts.admin ?? false, + super_admin: opts.superadmin ?? false, + scopes: opts.scope && opts.scope.length > 0 ? opts.scope : undefined, }, }); console.log(token); } +async function updateScopes( + opts: GlobalOptions & { scope?: string[]; clear?: boolean }, + tokenPrefix: string +) { + const scopes = opts.scope ?? []; + if (!!opts.clear === scopes.length > 0) { + throw new Error("Pass either one or more --scope, or --clear"); + } + opts = await mergeConfigWithConfigFile(opts); + await requireLogin(opts); + + await wmill.updateTokenScopes({ + tokenPrefix, + requestBody: { scopes: opts.clear ? null : scopes }, + }); + + log.info( + colors.green( + opts.clear + ? `Token with prefix '${tokenPrefix}' no longer has scope restrictions.` + : `Token with prefix '${tokenPrefix}' scoped to: ${scopes.join(" ")}` + ) + ); +} + async function deleteToken(opts: GlobalOptions, tokenPrefix: string) { opts = await mergeConfigWithConfigFile(opts); await requireLogin(opts); @@ -79,7 +135,30 @@ const command = new Command() .command("create", "Create a new API token") .option("--label <label:string>", "Token label") .option("--expiration <expiration:string>", "Token expiration (ISO 8601 timestamp)") + .option( + "--all-workspaces", + "Do not bind the token to the current workspace: it then reaches every workspace you are a member of and instance-level endpoints" + ) + .option("--admin", "Carry your workspace admin rights (off by default)") + .option("--superadmin", "Carry your superadmin rights (off by default)") + .option( + "--scope <scope:string>", + "Restrict the token to this scope (e.g. jobs:run, scripts:read:f/folder/*). Repeatable. Omit for no scope restriction.", + { collect: true } + ) .action(create as any) + .command("update-scopes", "Replace the scopes of one of your tokens, by its prefix") + .arguments("<token_prefix:string>") + .option( + "--scope <scope:string>", + "Scope the token is restricted to (e.g. jobs:run, scripts:read:f/folder/*). Repeatable; replaces all existing scopes.", + { collect: true } + ) + .option( + "--clear", + "Remove every scope restriction (the token keeps its workspace binding and admin/superadmin rights)" + ) + .action(updateScopes as any) .command("delete", "Delete a token by its prefix") .arguments("<token_prefix:string>") .action(deleteToken as any); diff --git a/cli/src/commands/user/user.ts b/cli/src/commands/user/user.ts index 946d943371..f0f8799687 100644 --- a/cli/src/commands/user/user.ts +++ b/cli/src/commands/user/user.ts @@ -134,7 +134,12 @@ async function remove(opts: GlobalOptions, email: string) { } async function createToken( - opts: GlobalOptions & { email: string; password: string } + opts: GlobalOptions & { + email: string; + password: string; + admin?: boolean; + superadmin?: boolean; + } ) { await requireLogin(opts); @@ -151,7 +156,15 @@ async function createToken( return; } - log.info("Token: " + (await wmill.createToken({ requestBody: {} }))); + log.info( + "Token: " + + (await wmill.createToken({ + requestBody: { + admin: opts.admin ?? false, + super_admin: opts.superadmin ?? false, + }, + })) + ); } interface SimplifiedUser { @@ -580,6 +593,8 @@ const command = new Command() depends: ["email"], } ) + .option("--admin", "Carry your workspace admin rights (off by default)") + .option("--superadmin", "Carry your superadmin rights (off by default)") .action(createToken as any); export default command; diff --git a/cli/src/commands/workspace/workspace.ts b/cli/src/commands/workspace/workspace.ts index 8c8b90cc24..df9a4c7aa3 100644 --- a/cli/src/commands/workspace/workspace.ts +++ b/cli/src/commands/workspace/workspace.ts @@ -1,5 +1,5 @@ import { writeFile, open as fsOpen } from "node:fs/promises"; -import { readTextFile } from "../../utils/utils.ts"; +import { isUnauthorized, readTextFile } from "../../utils/utils.ts"; import process from "node:process"; import { GlobalOptions } from "../../types.ts"; import type { WorkspaceEntryConfig } from "../../core/conf.ts"; @@ -30,6 +30,16 @@ export interface Workspace { token: string; } +/** Whether the current client's token is accepted in `workspaceId`. */ +async function worksInWorkspace(workspaceId: string): Promise<boolean> { + try { + await wmill.whoami({ workspace: workspaceId }); + return true; + } catch { + return false; + } +} + export async function allWorkspaces( configDirOverride?: string ): Promise<Workspace[]> { @@ -347,7 +357,7 @@ export async function add( return; } while (!token) { - token = await loginInteractive(remote); + token = await loginInteractive(remote, workspaceId); } setClient( @@ -360,10 +370,16 @@ export async function add( requestBody: { id: workspaceId }, }); } catch (e) { - log.info( - colors.red.bold("! Credentials or instance is invalid. Aborting.") - ); - throw e; + // A token bound to one workspace is refused on this instance-level route. If it works in + // the workspace being added, that workspace exists. + if (isUnauthorized(e) && (await worksInWorkspace(workspaceId))) { + alreadyExists = true; + } else { + log.info( + colors.red.bold("! Credentials or instance is invalid. Aborting.") + ); + throw e; + } } if (opts.create) { if (!alreadyExists) { @@ -610,7 +626,7 @@ async function login(opts: GlobalOptions, workspaceName?: string) { log.info( `Signing in again to ${workspace.workspaceId} on ${workspace.remote} for profile ${workspace.name}` ); - token = await loginInteractive(workspace.remote); + token = await loginInteractive(workspace.remote, workspace.workspaceId); } if (!token) { log.info(colors.red.bold("! Login failed, the profile was left unchanged.")); diff --git a/cli/src/core/auth.ts b/cli/src/core/auth.ts index 4ce903e875..55ca3841c4 100644 --- a/cli/src/core/auth.ts +++ b/cli/src/core/auth.ts @@ -130,7 +130,7 @@ export async function requireLogin( ? `! The token of workspace profile '${workspace.name}' has expired or was revoked. Sign in again to continue.` : "! Could not reach API given existing credentials. Attempting to reauth..." )); - const newToken = await loginInteractive(workspace.remote); + const newToken = await loginInteractive(workspace.remote, workspace.workspaceId); if (!newToken) { throw new Error( `Unauthorized: Could not authenticate with the provided credentials. Run 'wmill workspace login ${workspace.name}' in a terminal to sign in again.` diff --git a/cli/src/core/constants.ts b/cli/src/core/constants.ts index 217e10b177..ff2433b834 100644 --- a/cli/src/core/constants.ts +++ b/cli/src/core/constants.ts @@ -10,4 +10,4 @@ export const WM_FORK_PREFIX = "wm-fork"; // (e.g. utils.ts) can read it without importing main.ts and creating a circular // dependency (main → workspace → utils → main) that triggers a TDZ. // Re-exported from main.ts for backwards compatibility. -export const VERSION = "1.884.1"; +export const VERSION = "1.894.1"; diff --git a/cli/src/core/context.ts b/cli/src/core/context.ts index 80b27ea52e..4fa069949a 100644 --- a/cli/src/core/context.ts +++ b/cli/src/core/context.ts @@ -166,7 +166,7 @@ async function createWorkspaceProfileInteractively( default: workspaceId, }); - const token = await loginInteractive(normalizedBaseUrl); + const token = await loginInteractive(normalizedBaseUrl, workspaceId); if (!token) { log.error("Failed to obtain token"); return undefined; diff --git a/cli/src/core/login.ts b/cli/src/core/login.ts index 94a9ce11b8..f0cdb09859 100644 --- a/cli/src/core/login.ts +++ b/cli/src/core/login.ts @@ -7,7 +7,8 @@ import { Secret } from "@cliffy/prompt/secret"; import { Select } from "@cliffy/prompt/select"; import * as http from "node:http"; -export async function loginInteractive(remote: string) { +/** `workspace` names the workspace the token is for, so the login page can offer to bind it. */ +export async function loginInteractive(remote: string, workspace?: string) { let token: string | undefined; if (!process.stdin.isTTY) { log.infoStderr("Not a TTY, can't login interactively."); @@ -28,7 +29,7 @@ export async function loginInteractive(remote: string) { ], })) === "b" ) { - token = await browserLogin(remote); + token = await browserLogin(remote, workspace); } else { token = await Secret.prompt("Enter your token"); } @@ -46,7 +47,8 @@ export async function tryGetLoginInfo( } export async function browserLogin( - baseUrl: string + baseUrl: string, + workspace?: string ): Promise<string | undefined> { const env = process.env["TOKEN_PORT"] != undefined @@ -78,7 +80,9 @@ export async function browserLogin( resolve(token ?? undefined); }); - const url = `${baseUrl}user/cli?port=${port}`; + const url = + `${baseUrl}user/cli?port=${port}` + + (workspace ? `&workspace=${encodeURIComponent(workspace)}` : ""); log.infoStderr(`Login by going to ${url}`); try { diff --git a/cli/src/core/settings.ts b/cli/src/core/settings.ts index 719de7a96d..1546902fbe 100644 --- a/cli/src/core/settings.ts +++ b/cli/src/core/settings.ts @@ -103,6 +103,60 @@ export const SETTINGS_MANAGED_ONLY_WHEN_PRESENT = [ * so a file that still carries one must not show as differing from the workspace. */ export const RETIRED_SETTINGS = ["guest_access_enabled"] as const; +/** How the server's settings reads begin a secret they withheld (without `dangerouslyRevealSecrets`). */ +export const REDACTED_SECRET_PREFIX = "__REDACTED__"; + +function keepUnchangedLocalSecrets(redacted: any, revealed: any, local: any): any { + if (typeof redacted === "string" && redacted.startsWith(REDACTED_SECRET_PREFIX)) { + return local !== undefined && deepEqual(local, revealed) ? local : redacted; + } + if (Array.isArray(redacted)) { + return redacted.map((v, i) => + keepUnchangedLocalSecrets(v, revealed?.[i], local?.[i]) + ); + } + if (redacted && typeof redacted === "object") { + return Object.fromEntries( + Object.entries(redacted).map(([k, v]) => [ + k, + keepUnchangedLocalSecrets(v, revealed?.[k], local?.[k]), + ]) + ); + } + return redacted; +} + +/** + * The remote settings as pull and push compare them with the local file. Unless + * `showSecrets`, a remote secret stays redacted, except where the local file already holds + * that same value: comparing against the redacted value alone would flag every secret as + * changed on each sync, while the revealed one must not reach the printed diff or the file. + */ +async function remoteSettingsAgainstLocal( + opts: InstanceSyncOptions, + readLocal: () => Promise<GlobalSetting[]> +): Promise<GlobalSetting[]> { + if (opts.showSecrets) { + return await wmill.listGlobalSettings({ dangerouslyRevealSecrets: true }); + } + const redacted = await wmill.listGlobalSettings(); + if (!JSON.stringify(redacted).includes(REDACTED_SECRET_PREFIX)) { + return redacted; + } + const revealed = await wmill.listGlobalSettings({ + dangerouslyRevealSecrets: true, + }); + const local = await readLocal(); + return redacted.map((s) => ({ + ...s, + value: keepUnchangedLocalSecrets( + s.value, + revealed.find((r) => r.name === s.name)?.value, + local.find((l) => l.name === s.name)?.value + ), + })); +} + // Legacy settings interface for reading old settings.yaml files interface LegacySimplifiedSettings { auto_invite_enabled?: boolean; @@ -708,7 +762,10 @@ export async function pushWorkspaceKey( } } -export async function readInstanceSettings(opts: InstanceSyncOptions) { +export async function readInstanceSettings( + opts: InstanceSyncOptions, + silent = false +) { let localSettings: GlobalSetting[] = []; await checkInstanceSettingsPath(opts); @@ -718,7 +775,7 @@ export async function readInstanceSettings(opts: InstanceSyncOptions) { instanceSettingsPath )) as GlobalSetting[]; } catch { - log.warn(`No ${instanceSettingsPath} found`); + if (!silent) log.warn(`No ${instanceSettingsPath} found`); } return localSettings; } @@ -781,7 +838,22 @@ export async function pullInstanceSettings( opts: InstanceSyncOptions, preview = false ) { - const remoteSettings = await wmill.listGlobalSettings(); + const remoteSettings = await remoteSettingsAgainstLocal( + opts, + async () => + await processInstanceSettings( + await readInstanceSettings(opts, true), + "decode" + ) + ); + if ( + !preview && + JSON.stringify(remoteSettings).includes(REDACTED_SECRET_PREFIX) + ) { + log.info( + "Secrets are redacted in the pulled settings: pass --show-secrets to include them. Pushing them back keeps the stored secrets." + ); + } await checkInstanceSettingsPath(opts); @@ -818,9 +890,12 @@ export async function pushInstanceSettings( opts: InstanceSyncOptions, preview: boolean = false ) { - const remoteSettings = await wmill.listGlobalSettings(); let localSettings: GlobalSetting[] = await readInstanceSettings(opts); localSettings = await processInstanceSettings(localSettings, "decode"); + const remoteSettings = await remoteSettingsAgainstLocal( + opts, + async () => localSettings + ); if (opts.baseUrl) { localSettings = localSettings.filter((s) => s.name !== "base_url"); diff --git a/cli/src/guidance/skills.gen.ts b/cli/src/guidance/skills.gen.ts index f8eae5b499..ca220a6abe 100644 --- a/cli/src/guidance/skills.gen.ts +++ b/cli/src/guidance/skills.gen.ts @@ -6295,6 +6295,7 @@ can call one, not an agent used as a tool. ## Loop Structure Rules - 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 +- To carry on past failed iterations only up to a budget (e.g. a rollout over many targets), set \`skip_failures: true\` with \`failure_threshold\` on the \`forloopflow\` or \`whileloopflow\` value: the loop fails with \`{ error: { name: "FailureThresholdReached", message } }\` once that many iterations have failed. It takes a whole number of at least 1, or an input transform evaluated once when the loop starts that returns one, e.g. \`{ type: "javascript", expr: "Math.ceil(flow_input.targets.length * 0.1)" }\` for 10%. A parallel loop then cancels the iterations no worker has picked up yet, including those held back by \`parallelism\`, while iterations already picked up finish, so set \`parallelism\` to bound how many are in flight when the threshold is reached - When iterations are items a user will look for in a run (customers, files, ids), set \`iteration_label\` on the \`forloopflow\` value to a javascript expression naming each one, e.g. \`flow_input.iter.value.name\`; it only labels iterations in the run viewer and never changes what runs - 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) - \`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 @@ -6612,7 +6613,7 @@ Reference a specific resource using \`$res:\` prefix: ## OpenFlow Schema -{"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-<type>' (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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this flow does when its concurrency limit is reached. \`queue\` (default) re-queues it to a later slot, \`fail\` ends it immediately as failed, like any failed step."},"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"},"timeout":{"type":"integer","description":"Wall-clock limit in seconds for the whole flow run, counted from its start and including time spent sleeping or suspended at an approval. It also applies when the flow is called as a subflow step, unless that step sets its own timeout, which replaces it. It is checked periodically, so a run can go a few seconds past it. When it expires, the running steps are cancelled, the failure module runs if there is one, and the flow ends cancelled with a timeout error. A calling flow sees the subflow step fail with that error."},"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.<step_id>'"}},"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"},"preview_only":{"type":"boolean","description":"If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run."}}},"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/<flow_path>-<step_id>"},"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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this step does when its concurrency limit is reached. \`queue\` (default) re-queues it to a later slot, \`fail\` ends it immediately as failed."},"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')"},"tag_override":{"type":"string","description":"Override the subflow's worker group tag. Its steps run on this tag unless the subflow sets preserve_step_tags"},"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"},"iteration_label":{"description":"Optional expression evaluated once per iteration into the label the run viewers show for it, e.g. 'flow_input.iter.value.name'. It can reference 'flow_input.iter' and 'results'. Purely informational, a failing expression leaves the iteration unlabelled and never fails it. Labels are capped at 100 characters","$ref":"#/components/schemas/InputTransform"}},"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.<its_own_id>' 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"},"max_iterations":{"type":"integer","minimum":1,"description":"Maximum number of iterations. Checked after each iteration; when reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"},"max_duration_secs":{"type":"integer","minimum":1,"description":"Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"}},"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"},"parallelism":{"description":"Maximum number of branches running at once when parallel=true. Can be static number or expression","$ref":"#/components/schemas/InputTransform"}},"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."},"background":{"type":"boolean","description":"Flowmodule tools only. The agent is answered as soon as the tool's job starts and keeps working; the job's result reaches it in a later message. If the agent finishes its answer first, it stops without holding a worker until the job is done, then continues with the result."},"background_after_secs":{"type":"integer","minimum":1,"description":"Flowmodule tools only, with background unset. The agent waits up to this many seconds for the tool's job and gets its result as usual; a job still running then continues as a background one, its result reaching the agent in a later message."},"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 or Gemini'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: { <question name>: answer },\\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\\nthe answers, follow it with a branchone whose branch exprs read\\nresults.<id>.output.<question>.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"}}}},"continued_on_error":{"type":"array","description":"On a root flow, the steps at any depth that failed and that the flow went past because of continue_on_error (at most 100).","items":{"type":"object","properties":{"id":{"type":"string"},"job":{"type":"string","format":"uuid"}},"required":["id","job"]}},"test_subflows":{"type":"object","description":"In a flow test run, deployed subflow path -> the flow value with the test's step overrides applied, run in place of the deployed subflow.","additionalProperties":{"type":"object"}}},"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_labels":{"type":"array","description":"For a for-loop step whose iteration_label is set, each iteration's label, aligned with flow_jobs. An entry is null when its label evaluated to nothing","items":{"type":"string","nullable":true}},"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","description":"The outcome of each agent action, by position. null while a background tool call is still running.","items":{"type":"boolean","nullable":true}}},"required":["type"]}} +{"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-<type>' (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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this flow does when its concurrency limit is reached. \`queue\` (default) re-queues it to a later slot, \`fail\` ends it immediately as failed, like any failed step."},"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"},"timeout":{"type":"integer","description":"Wall-clock limit in seconds for the whole flow run, counted from its start and including time spent sleeping or suspended at an approval. It also applies when the flow is called as a subflow step, unless that step sets its own timeout, which replaces it. It is checked periodically, so a run can go a few seconds past it. When it expires, the running steps are cancelled, the failure module runs if there is one, and the flow ends cancelled with a timeout error. A calling flow sees the subflow step fail with that error."},"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.<step_id>'"}},"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"},"preview_only":{"type":"boolean","description":"If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run."}}},"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"},"show_on_home":{"type":"boolean","description":"If true, a run waiting on this step is listed on the Home page of each user who can approve it. Leave unset when the approval request is sent through another channel (Slack, Discord, email), so it does not sit there unanswered"}}},"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/<flow_path>-<step_id>"},"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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this step does when its concurrency limit is reached. \`queue\` (default) re-queues it to a later slot, \`fail\` ends it immediately as failed."},"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')"},"tag_override":{"type":"string","description":"Override the subflow's worker group tag. Its steps run on this tag unless the subflow sets preserve_step_tags"},"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"},"failure_threshold":{"description":"With skip_failures, the loop fails with an error named 'FailureThresholdReached' as soon as this many iterations have failed. Static number or expression (e.g. 'Math.ceil(flow_input.targets.length * 0.1)' for a percentage), evaluated once when the loop starts. A sequential loop stops at the iteration that reaches it. A parallel loop cancels the iterations no worker has picked up yet, including those held back by parallelism, while iterations already picked up finish; set parallelism to bound how many are in flight when the threshold is reached","$ref":"#/components/schemas/InputTransform"},"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"},"iteration_label":{"description":"Optional expression evaluated once per iteration into the label the run viewers show for it, e.g. 'flow_input.iter.value.name'. It can reference 'flow_input.iter' and 'results'. Purely informational, a failing expression leaves the iteration unlabelled and never fails it. Labels are capped at 100 characters","$ref":"#/components/schemas/InputTransform"}},"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.<its_own_id>' 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"},"max_iterations":{"type":"integer","minimum":1,"description":"Maximum number of iterations. Checked after each iteration; when reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"},"max_duration_secs":{"type":"integer","minimum":1,"description":"Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"},"failure_threshold":{"description":"With skip_failures, the loop fails with an error named 'FailureThresholdReached' at the iteration that brings the failed iterations to this count. Static number or expression, evaluated once when the loop starts","$ref":"#/components/schemas/InputTransform"}},"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"},"parallelism":{"description":"Maximum number of branches running at once when parallel=true. Can be static number or expression","$ref":"#/components/schemas/InputTransform"}},"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."},"background":{"type":"boolean","description":"Flowmodule tools only. The agent is answered as soon as the tool's job starts and keeps working; the job's result reaches it in a later message. If the agent finishes its answer first, it stops without holding a worker until the job is done, then continues with the result."},"background_after_secs":{"type":"integer","minimum":1,"description":"Flowmodule tools only, with background unset. The agent waits up to this many seconds for the tool's job and gets its result as usual; a job still running then continues as a background one, its result reaching the agent in a later message."},"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 or Gemini'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: { <question name>: answer },\\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\\nthe answers, follow it with a branchone whose branch exprs read\\nresults.<id>.output.<question>.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"}}}},"continued_on_error":{"type":"array","description":"On a root flow, the steps at any depth that failed and that the flow went past because of continue_on_error (at most 100).","items":{"type":"object","properties":{"id":{"type":"string"},"job":{"type":"string","format":"uuid"}},"required":["id","job"]}},"test_subflows":{"type":"object","description":"In a flow test run, deployed subflow path -> the flow value with the test's step overrides applied, run in place of the deployed subflow.","additionalProperties":{"type":"object"}}},"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_labels":{"type":"array","description":"For a for-loop step whose iteration_label is set, each iteration's label, aligned with flow_jobs. An entry is null when its label evaluated to nothing","items":{"type":"string","nullable":true}},"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"},"approved_at":{"type":"string","format":"date-time","description":"absent for approvals recorded before it was kept"},"approved":{"type":"boolean","description":"false for a rejection the flow continued past; absent for approvals recorded before it was kept\\n"}},"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","description":"The outcome of each agent action, by position. null while a background tool call is still running.","items":{"type":"boolean","nullable":true}}},"required":["type"]}} `, "raw-app": `--- name: raw-app @@ -8659,7 +8660,7 @@ write a secret you were not given: keep the placeholder. | \`git_sync\` | \`{ repositories: [...] }\`, each with \`git_repo_resource_path\`, \`script_path\` and \`settings\` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. | | \`datatable\` | \`{ datatables: { <name>: { database: { resource_type, resource_path } } } }\`, both required: \`resource_type: postgresql\` with \`resource_path\` a Postgres resource's path, or \`instance\`, or \`external_instance\` (Enterprise only), with \`resource_path\` the name of a database a superadmin set up. A fork's entry can instead be \`{ reference: { workspace_id, datatable } }\`, pointing at its parent's data table; keep it as is. \`main\` is the one scripts use by default. Role permissions are \`datatable_permissions\`. | | \`datatable_permissions\` | \`{ <data table>: { default_role, roles: { <role>: [tenants] } } }\`: who may connect to each data table as which role. Tenants are \`u/<user>\`, \`g/<group>\`, \`f/<folder>\` or \`*\`; \`admin\` is always a role, and \`default_role: null\` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. | -| \`protection_rules\` | \`{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { <role here>: <role in its forks> } } }\`, rules among \`DisableDirectDeployment\`, \`DisableWorkspaceForking\`, \`RestrictDeployToDeployers\`, \`RestrictAnonymousAppDeployment\`, \`RestrictPublicRunSharing\`, \`RestrictGuestAppDeployment\`, \`RequireIsolatedForks\`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | +| \`protection_rules\` | \`{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { <role here>: <role in its forks> } } }\`, rules among \`DisableDirectDeployment\`, \`DisableWorkspaceForking\`, \`RestrictDeployToDeployers\`, \`RestrictAnonymousAppDeployment\`, \`RestrictPublicRunSharing\`, \`RestrictGuestAppDeployment\`, \`RequireIsolatedForks\`, \`RequireSso\` (an account signing in with a password, other than a bypasser, cannot join, and no member can be switched to a password login; members already signing in with a password are not removed). A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | | \`ducklake\` | \`{ ducklakes: { <name>: { catalog, storage, ... } } }\`. | | \`dbt_warehouses\` | dbt warehouse connections. | | \`default_app\` | Path of the app shown as the workspace home. | @@ -8762,6 +8763,15 @@ of the shapes below is shown as JSON. Each shape is an object with that one key (plus \`filename\` for a file, and an optional \`storage\` for \`s3\`). A result carrying any other key beside it is shown as JSON. +## Large results + +A result stored above about 90 KB is not sent with the run: the run page and the editors offer it +as a JSON download, with a Load button that draws it on request. A \`render_all\` lists up to 100 of +its elements with their type and size, counts the rest, and loads them ten at a time. To have a large result previewed without a +click, write the content to the workspace storage and return \`{ "s3": "path/to/key" }\`, which is +previewed by type; for a generated image, also keep it small (a JPEG, or fewer pixels) when it only +needs to be looked at. + ## Choosing one A chart answers a question at a glance: a trend over time (line), a comparison across categories @@ -8912,12 +8922,14 @@ app related commands - \`--host <host:string>\` - Host to bind the dev server to - \`--entry <entry:string>\` - Entry point file (default: index.ts for Svelte, index.tsx otherwise) - \`--no-open\` - Don't automatically open the browser + - \`--run-install-scripts\` - Run the dependencies' lifecycle scripts when installing node_modules - \`--recording\` - Frame the app in a shell with a Record button, to capture a replayable session recording of the app under development - \`app lint [app_folder:string]\` - Lint a raw app folder to validate structure and buildability - \`--fix\` - Attempt to fix common issues (not implemented yet) - \`app bundle [app_folder:string]\` - Bundle a raw app folder to js/css without deploying it - \`--out <dir:string>\` - Directory to write bundle.js and bundle.css into (default: <app_folder>/dist) - \`--no-minify\` - Skip minification + - \`--run-install-scripts\` - Run the dependencies' lifecycle scripts when installing node_modules - \`app new\` - create a new raw app from a template - \`--summary <summary:string>\` - App summary (short description). Skips the prompt when provided. Triggers non-interactive mode. - \`--path <path:string>\` - App path (e.g., f/folder/my_app or u/username/my_app). Skips the prompt when provided. Triggers non-interactive mode. @@ -9005,6 +9017,7 @@ Watch local file changes and live-reload the dev page for preview. Does NOT depl - \`--proxy-port <port:number>\` - Port for a localhost reverse proxy to the remote Windmill server - \`--path <path:string>\` - Watch a specific windmill path (e.g., u/admin/my_script or f/my_flow) - \`--no-open\` - Do not open the browser automatically +- \`--host <host:string>\` - Address to bind the dev server to: a loopback address or 0.0.0.0 for every interface (default: 127.0.0.1, this machine only) ### digest @@ -9205,6 +9218,7 @@ sync local with a remote instance or the opposite (push or pull) - \`--dry-run\` - Perform a dry run without making changes - \`--skip-users\` - Skip pulling users - \`--skip-settings\` - Skip pulling settings + - \`--show-secrets\` - Pull secrets (license key, passwords, tokens) in clear instead of redacted - \`--skip-configs\` - Skip pulling configs (worker groups) - \`--skip-groups\` - Skip pulling instance groups - \`--include-workspaces\` - Also pull workspaces @@ -9227,7 +9241,7 @@ sync local with a remote instance or the opposite (push or pull) - \`instance whoami\` - Display information about the currently logged-in user - \`instance get-config\` - Dump the current instance config (global settings + worker configs) as YAML - \`-o, --output-file <file:string>\` - Write YAML to a file instead of stdout - - \`--show-secrets\` - Include sensitive fields (license key, JWT secret) without prompting + - \`--show-secrets\` - Include secrets (license key, passwords, tokens) in clear without prompting - \`--instance <instance:string>\` - Name of the instance, override the active instance - \`instance connect-slack\` - Non-interactively connect Slack at the instance level using a pre-minted bot token (xoxb-...). Produces the same artifacts as the UI OAuth flow: global_settings 'slack' row + encrypted f/slack_bot/global_bot_token variable and resource in the admins workspace. - \`--bot-token <bot_token:string>\` - Slack bot token (xoxb-...) @@ -9580,6 +9594,13 @@ Manage API tokens - \`token create\` - Create a new API token - \`--label <label:string>\` - Token label - \`--expiration <expiration:string>\` - Token expiration (ISO 8601 timestamp) + - \`--all-workspaces\` - Do not bind the token to the current workspace: it then reaches every workspace you are a member of and instance-level endpoints + - \`--admin\` - Carry your workspace admin rights (off by default) + - \`--superadmin\` - Carry your superadmin rights (off by default) + - \`--scope <scope:string>\` - Restrict the token to this scope (e.g. jobs:run, scripts:read:f/folder/*). Repeatable. Omit for no scope restriction. +- \`token update-scopes <token_prefix:string>\` - Replace the scopes of one of your tokens, by its prefix + - \`--scope <scope:string>\` - Scope the token is restricted to (e.g. jobs:run, scripts:read:f/folder/*). Repeatable; replaces all existing scopes. + - \`--clear\` - Remove every scope restriction (the token keeps its workspace binding and admin/superadmin rights) - \`token delete <token_prefix:string>\` - Delete a token by its prefix ### trash @@ -9639,6 +9660,8 @@ user related commands - \`user create-token\` - Create a new API token for the authenticated user - \`--email <email:string>\` - Specify credentials to use for authentication. This will not be stored. It will only be used to exchange for a token with the API server, which will not be stored either. - \`--password <password:string>\` - Specify credentials to use for authentication. This will not be stored. It will only be used to exchange for a token with the API server, which will not be stored either. + - \`--admin\` - Carry your workspace admin rights (off by default) + - \`--superadmin\` - Carry your superadmin rights (off by default) ### variable diff --git a/cli/src/main.ts b/cli/src/main.ts index 1632d4d7e3..eefaa7d9f5 100755 --- a/cli/src/main.ts +++ b/cli/src/main.ts @@ -33,6 +33,8 @@ import { GlobalOptions } from "./types.ts"; import { OpenAPI } from "../gen/index.ts"; import { apiErrorMessage, + BOUND_TOKEN_HINT, + isUnauthorized, getHeaders, networkErrorMessage, } from "./utils/utils.ts"; @@ -335,6 +337,9 @@ async function main() { const networkError = networkErrorMessage(e); if (apiError !== undefined) { log.error("Server failed. " + apiError); + if (isUnauthorized(e)) { + log.infoStderr(BOUND_TOKEN_HINT); + } } else if (networkError !== undefined) { log.error(networkError); } else if (e instanceof Error) { diff --git a/cli/src/utils/dev_server_access.ts b/cli/src/utils/dev_server_access.ts new file mode 100644 index 0000000000..f20268c0e1 --- /dev/null +++ b/cli/src/utils/dev_server_access.ts @@ -0,0 +1,96 @@ +/** + * Who may talk to the local dev servers (`wmill dev`, `wmill app dev`). Their + * WebSockets act on the developer's files and Windmill token, and a browser + * lets a page of any origin open `ws://localhost:<port>`, so the upgrade is + * gated on the headers a page cannot choose: `Origin` and `Host`. + */ + +import * as path from "node:path"; +import { isIP } from "node:net"; + +const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]); + +export function isLoopbackHostname(hostname: string): boolean { + return LOOPBACK_HOSTNAMES.has(hostname.toLowerCase()); +} + +/** + * Whether a server bound to `host` answers on `localhost`, which is where the + * dev page connects: a loopback address, or every interface. + */ +export function bindsLocalhost(host: string): boolean { + return isLoopbackHostname(host) || host === "0.0.0.0" || host === "::" || host === "[::]"; +} + +/** Whether `origin` is a page served from this machine (any loopback port). */ +export function isLoopbackOrigin(origin: string): boolean { + try { + const u = new URL(origin); + return ( + (u.protocol === "http:" || u.protocol === "https:") && + isLoopbackHostname(u.hostname) + ); + } catch { + return false; + } +} + +/** + * Whether the `Host` header names this server under a name that cannot have + * been re-pointed at it by DNS: a loopback name, an IP literal, or the host + * the server was explicitly bound to. A server bound to a wildcard address is + * reachable by any name the developer chose to expose, so any Host passes. + */ +export function isAllowedHostHeader( + host: string | undefined, + bindHost: string, +): boolean { + if (bindHost === "0.0.0.0" || bindHost === "::") return true; + if (host === undefined) return false; + let hostname: string; + try { + hostname = new URL(`http://${host}`).hostname; + } catch { + return false; + } + const bare = hostname.replace(/^\[|\]$/g, ""); + return ( + isLoopbackHostname(hostname) || + isIP(bare) !== 0 || + hostname.toLowerCase() === bindHost.toLowerCase() + ); +} + +/** + * Whether a browser page of `origin` may open the `wmill dev` socket: the + * workspace remote (where the dev page is served) or a page on this machine + * (the `--proxy-port` proxy, a locally run frontend). No Origin is a + * non-browser client; a forged one is no worse than no header at all. + */ +export function isAllowedDevPageOrigin( + origin: string | undefined, + remote: string, +): boolean { + if (origin === undefined) return true; + if (isLoopbackOrigin(origin)) return true; + try { + return new URL(origin).origin === new URL(remote).origin; + } catch { + return false; + } +} + +/** Whether `p` resolves to `folder` or somewhere below it. Both are taken + * relative to the current directory, as the dev server's paths are. */ +export function isWithinFolder(folder: string, p: string): boolean { + const rel = path.relative(path.resolve(folder), path.resolve(p)); + return !(rel === ".." || rel.startsWith(".." + path.sep) || path.isAbsolute(rel)); +} + +const UUID_RE = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +/** Job ids are UUIDs; anything else must not reach a URL path. */ +export function isJobId(id: unknown): id is string { + return typeof id === "string" && UUID_RE.test(id); +} diff --git a/cli/src/utils/metadata.ts b/cli/src/utils/metadata.ts index 711d510f96..8f5490815c 100644 --- a/cli/src/utils/metadata.ts +++ b/cli/src/utils/metadata.ts @@ -33,7 +33,7 @@ import { } from "./script_common.ts"; import { dbtGeneratedDirs, isUnderGeneratedDir, isBundledModuleFile, getModuleFolderSuffix, isModuleEntryPoint, scriptPathToRemotePath } from "./resource_folders.ts"; import { findCodebase, yamlOptions } from "../commands/sync/sync.ts"; -import { generateHash, readInlinePathSync, getHeaders, readTextFile, readTextFileSync } from "./utils.ts"; +import { generateHash, inlinePathWithin, readInlinePathSync, getHeaders, readTextFile, readTextFileSync } from "./utils.ts"; import { DBT_DESCRIPTOR_NAME, isMissingDbtDescriptor } from "./resource_folders.ts"; import { detectAuthGatewayChallenge } from "./http_guards.ts"; @@ -169,9 +169,10 @@ export async function filterWorkspaceDependenciesForScripts( // Resolve !inline reference to actual content if (content.startsWith("!inline ")) { - const filePath = folder + sep + content.replace("!inline ", ""); try { - content = await readTextFile(filePath); + content = await readTextFile( + inlinePathWithin(content.replace("!inline ", ""), folder), + ); } catch { continue; } @@ -229,12 +230,15 @@ export async function generateScriptMetadataInternal( // the metadata sync actually reads untouched. const metadataInFolder = isFolderLayout && language !== "dbt"; - // For folder layout, parseMetadataFile is called with remotePath which - // will find __mod/script.yaml via the folder layout fallback - const metadataWithType = await parseMetadataFile( - remotePath, - undefined, - ); + // A tree run's dry pass only detects staleness; it must not create missing + // metadata, or a folder-scoped run writes files for every script it walks. + // A script without metadata is stale, and the generation pass creates it. + const detectOnly = tree !== undefined && dryRun && !opts.rehashOnly; + // For folder layout, the lookup uses remotePath, which finds + // __mod/script.yaml via the folder layout fallback + const existingMetadata = detectOnly + ? await findMetadataFile(remotePath) + : await parseMetadataFile(remotePath, undefined); // read script content — a dbt project's descriptor is optional, and absent // means an empty descriptor rather than a script that cannot be pushed. @@ -242,7 +246,9 @@ export async function generateScriptMetadataInternal( if (isMissingDbtDescriptor(scriptPath, e)) return ""; throw e; }); - const metadataContent = await readTextFile(metadataWithType.path); + const metadataContent = existingMetadata + ? await readTextFile(existingMetadata.path) + : ""; const filteredRawWorkspaceDependencies = filterWorkspaceDependencies( rawWorkspaceDependencies, @@ -306,7 +312,8 @@ export async function generateScriptMetadataInternal( } // Use checkHash (includes module hashes) so module changes are detected as stale - const isDirectlyStale = !(await checkifMetadataUptodate(remotePath, checkHash, conf, checkSubpath)); + const isDirectlyStale = !existingMetadata || + !(await checkifMetadataUptodate(remotePath, checkHash, conf, checkSubpath)); // Tree-based dependency tracking if (tree) { @@ -347,6 +354,9 @@ export async function generateScriptMetadataInternal( log.info(colors.gray(`Generating metadata for ${scriptPath}`)); } + const metadataWithType = existingMetadata ?? + (await parseMetadataFile(remotePath, undefined)); + const metadataParsedContent = metadataWithType?.payload as Record< string, any @@ -1088,18 +1098,10 @@ export async function parseMetadataFileIfExists( } } -export async function parseMetadataFile( - scriptPath: string, - generateMetadataIfMissing: - | (GlobalOptions & { - path: string; - workspaceRemote: Workspace; - schemaOnly?: boolean; - rawWorkspaceDependencies: Record<string, string>; - codebases: SyncCodebase[] - }) - | undefined -): Promise<{ isJson: boolean; payload: any; path: string }> { +/** The script's metadata file, flat or folder layout, or undefined when it has none. */ +async function findMetadataFile( + scriptPath: string +): Promise<{ isJson: boolean; payload: any; path: string } | undefined> { let metadataFilePath = scriptPath + ".script.json"; try { await stat(metadataFilePath); @@ -1143,13 +1145,29 @@ export async function parseMetadataFile( isJson: false, }; } catch { - // fall through to create metadata + return undefined; } } } } +} + +export async function parseMetadataFile( + scriptPath: string, + generateMetadataIfMissing: + | (GlobalOptions & { + path: string; + workspaceRemote: Workspace; + schemaOnly?: boolean; + rawWorkspaceDependencies: Record<string, string>; + codebases: SyncCodebase[] + }) + | undefined +): Promise<{ isJson: boolean; payload: any; path: string }> { + const existing = await findMetadataFile(scriptPath); + if (existing) return existing; // no metadata file at all. Create it - metadataFilePath = scriptPath + ".script.yaml"; + const metadataFilePath = scriptPath + ".script.yaml"; log.info( (await blueColor())( `Creating script metadata file for ${metadataFilePath}` diff --git a/cli/src/utils/port-probe.ts b/cli/src/utils/port-probe.ts index 3495e5de96..cfff4cfd10 100644 --- a/cli/src/utils/port-probe.ts +++ b/cli/src/utils/port-probe.ts @@ -143,8 +143,11 @@ export async function resolveBindPort( } /** - * The host string we bind to. Explicit IPv4 — `localhost` resolves to - * 127.0.0.1 first on every platform we care about, and binding both stacks - * relies on platform-specific IPV6_V6ONLY behaviour we don't want to debug. + * The host string `wmill dev` binds to unless `--host` says otherwise. + * Loopback only: the server reads and writes the checkout's files (and, in + * proxy mode, hands out the workspace token), so it must not be reachable from + * the network. Explicit IPv4 — `localhost` resolves to 127.0.0.1 first on + * every platform we care about, and binding both stacks relies on + * platform-specific IPV6_V6ONLY behaviour we don't want to debug. */ -export const BIND_HOST = "0.0.0.0" as const; +export const BIND_HOST = "127.0.0.1" as const; diff --git a/cli/src/utils/utils.ts b/cli/src/utils/utils.ts index 9bc2751d11..69b42f5f89 100644 --- a/cli/src/utils/utils.ts +++ b/cli/src/utils/utils.ts @@ -4,9 +4,9 @@ import { colors } from "@cliffy/ansi/colors"; import * as log from "../core/log.ts"; -import { sep as SEP } from "node:path"; +import nodePath, { sep as SEP } from "node:path"; import crypto from "node:crypto"; -import { readFileSync, writeFileSync } from "node:fs"; +import { readFileSync, realpathSync, writeFileSync } from "node:fs"; import { readdir, readFile } from "node:fs/promises"; import { fetchVersion } from "../core/context.ts"; import { updateGlobalVersions } from "../commands/sync/global.ts"; @@ -176,9 +176,50 @@ export function readTextFileSync(path: string | URL): string { return decodeBufferAsUtf8(readFileSync(path), path); } -export function readInlinePathSync(path: string): string { +function isWithin(base: string, target: string): boolean { + const rel = nodePath.relative(base, target); + return ( + rel !== "" && + rel !== ".." && + !rel.startsWith(".." + SEP) && + !nodePath.isAbsolute(rel) + ); +} + +/** + * Resolve an `!inline` reference against `root` (the sync root by default) and + * refuse one that lands outside it, directly or through a symlink. References + * are tracked data a pull can write verbatim, so following one must never read + * a file the checkout does not hold. + */ +export function inlinePathWithin(ref: string, root: string = "."): string { + const base = nodePath.resolve(root); + const target = nodePath.resolve(base, ref.replaceAll("/", SEP)); + let inside = isWithin(base, target); + if (inside) { + let realBase: string; + let realTarget: string; + try { + realBase = realpathSync(base); + realTarget = realpathSync(target); + } catch { + // Nothing to follow yet: the caller's read reports the missing file. + return target; + } + inside = isWithin(realBase, realTarget); + } + if (!inside) { + throw new Error( + `'!inline ${ref}' refers to a file outside ${base}; inline references must stay within it`, + ); + } + return target; +} + +export function readInlinePathSync(path: string, root: string = "."): string { + const target = inlinePathWithin(path, root); try { - return readTextFileSync(path.replaceAll("/", SEP)); + return readTextFileSync(target); } catch (error) { log.warn(`Error reading inline path: ${path}, ${error}`); return ""; @@ -354,6 +395,26 @@ export function formatTimestamp(ts: string): string { return new Date(ts).toISOString().replace("T", " ").substring(0, 19); } +/** Whether the server refused the request's credential (HTTP 401). */ +export function isUnauthorized(e: unknown): boolean { + return ( + !!e && + typeof e === "object" && + "name" in e && + e.name === "ApiError" && + (e as { status?: number }).status === 401 + ); +} + +/** + * The server does not say why it refused a token, so this only names the likely cause for a + * token that worked before: one bound to a single workspace is refused everywhere else. + */ +export const BOUND_TOKEN_HINT = + "If this token was created for a single workspace, other workspaces and instance-level " + + "commands refuse it: log in again and pick 'All workspaces' on the login page, or create " + + "one with `wmill token create --all-workspaces`."; + /** * "<status text>: <body>" for an error thrown by the generated API client, * undefined for anything else. Backend source references such as diff --git a/cli/test/audit_token_commands.test.ts b/cli/test/audit_token_commands.test.ts index 66cc0b752f..5588bfa1e5 100644 --- a/cli/test/audit_token_commands.test.ts +++ b/cli/test/audit_token_commands.test.ts @@ -165,6 +165,49 @@ describe("token command", () => { }); }); + test("token create --scope + update-scopes", async () => { + await withTestBackend(async (backend, tempDir) => { + await setupWorkspaceProfile(backend); + const scopesOf = async () => { + const r = await backend.runCLICommand(["token", "list", "--json"], tempDir); + return JSON.parse(r.stdout).find((t: any) => t.label === "cli-scoped-token"); + }; + + // A scope carrying a comma must survive as one scope. + const created = await backend.runCLICommand( + [ + "token", "create", "--label", "cli-scoped-token", + "--scope", "jobs:run", "--scope", "mcp:workspaces:a,b", + ], + tempDir + ); + expect(created.code).toEqual(0); + const token = await scopesOf(); + expect(token.scopes).toEqual(["jobs:run", "mcp:workspaces:a,b"]); + + const narrowed = await backend.runCLICommand( + ["token", "update-scopes", token.token_prefix, "--scope", "scripts:read"], + tempDir + ); + expect(narrowed.code).toEqual(0); + expect((await scopesOf()).scopes).toEqual(["scripts:read"]); + + const noFlag = await backend.runCLICommand( + ["token", "update-scopes", token.token_prefix], + tempDir + ); + expect(noFlag.code).not.toEqual(0); + expect((await scopesOf()).scopes).toEqual(["scripts:read"]); + + const cleared = await backend.runCLICommand( + ["token", "update-scopes", token.token_prefix, "--clear"], + tempDir + ); + expect(cleared.code).toEqual(0); + expect((await scopesOf()).scopes ?? null).toBeNull(); + }); + }); + test("default action (wmill token) lists tokens", async () => { await withTestBackend(async (backend, tempDir) => { await setupWorkspaceProfile(backend); diff --git a/cli/test/dbt_module_tracker_unit.test.ts b/cli/test/dbt_module_tracker_unit.test.ts index 90abee18ae..c587cb9b62 100644 --- a/cli/test/dbt_module_tracker_unit.test.ts +++ b/cli/test/dbt_module_tracker_unit.test.ts @@ -142,4 +142,19 @@ describe("buildTracker with a dbt project", () => { expect(isDbtGeneratedPath("f/analytics/analytics__dbt/.env")).toBe(true); expect(isDbtGeneratedPath("f/analytics/analytics__dbt/models/stg.sql")).toBe(false); }); + + test("a resource stored under the project folder is not bundled", async () => { + const project = path.join(dir, "f/analytics/analytics__dbt"); + fs.mkdirSync(path.join(project, "models/notes.fileset"), { recursive: true }); + fs.writeFileSync(path.join(project, "models/notes.fileset/copy.sql"), "select 2"); + fs.writeFileSync(path.join(project, "models/notes.resource.yaml"), "value: {}\n"); + fs.writeFileSync(path.join(project, "models/q.resource.file.sql"), "select 3"); + fs.writeFileSync(path.join(project, "models/stg.sql"), "select 1"); + + const modules = await readModulesFromDisk(project, undefined, false, true); + expect(Object.keys(modules ?? {}).sort()).toEqual([ + "dbt_project.yml", + "models/stg.sql", + ]); + }); }); diff --git a/cli/test/deploy_labels_unit.test.ts b/cli/test/deploy_labels_unit.test.ts index f630500a62..ecb0dcd499 100644 --- a/cli/test/deploy_labels_unit.test.ts +++ b/cli/test/deploy_labels_unit.test.ts @@ -73,6 +73,33 @@ test("deployItem: carries labels for variables, resources and folders", async () } }); +test("deployItem: keeps the target's labels when the source has none set", async () => { + // Forks can hold items whose labels were never copied; only an explicit [] is a clear. + for (const labels of [undefined, []]) { + const bodies: any[] = []; + const write = async (p: any) => void bodies.push(p.requestBody); + const provider = { + existsVariable: async () => true, + existsResource: async () => true, + existsFlowByPath: async () => true, + existsApp: async () => true, + getVariable: async () => ({ value: "v", is_secret: false, labels }), + getResource: async () => ({ value: {}, resource_type: "postgresql", labels }), + getFlowByPath: async () => ({ path: "f/x/i", value: { modules: [] }, labels }), + getAppByPath: async () => ({ path: "f/x/i", policy: {}, labels }), + updateVariable: write, + updateResource: write, + updateFlow: write, + updateApp: write, + } as any; + for (const kind of ["variable", "resource", "flow", "app"]) { + const result = await deployItem(provider, kind as any, "f/x/i", "src", "dst"); + expect(result).toEqual({ success: true }); + } + expect(bodies.map((b) => b.labels)).toEqual([labels, labels, labels, labels]); + } +}); + test("deployItem: carries a resource type's file settings and clears unset ones", async () => { const bodies: Record<string, any> = {}; const deploy = (exists: boolean, rt: any) => diff --git a/cli/test/dev_server.test.ts b/cli/test/dev_server.test.ts index b4f630b3fa..75dbc3700e 100644 --- a/cli/test/dev_server.test.ts +++ b/cli/test/dev_server.test.ts @@ -167,6 +167,19 @@ test( expect(port).toBeGreaterThan(0); stdoutReader.releaseLock(); + // Only the dev page's origins may open the socket. + const foreignOpened = await new Promise<boolean>((resolve) => { + const foreign = new WebSocket(`ws://localhost:${port}`, { + headers: { Origin: "https://example.com" }, + }); + foreign.on("open", () => { + foreign.close(); + resolve(true); + }); + foreign.on("error", () => resolve(false)); + }); + expect(foreignOpened).toBe(false); + // Connect WebSocket ws = new WebSocket(`ws://localhost:${port}`); diff --git a/cli/test/dev_server_access_unit.test.ts b/cli/test/dev_server_access_unit.test.ts new file mode 100644 index 0000000000..a39527e386 --- /dev/null +++ b/cli/test/dev_server_access_unit.test.ts @@ -0,0 +1,67 @@ +/** + * Which clients the local dev servers (`wmill dev`, `wmill app dev`) accept + * on their WebSocket, and which paths and job ids their messages may name. + */ + +import { expect, test } from "bun:test"; +import * as path from "node:path"; +import { + bindsLocalhost, + isAllowedDevPageOrigin, + isAllowedHostHeader, + isJobId, + isWithinFolder, +} from "../src/utils/dev_server_access.ts"; + +test("the wmill dev socket accepts the dev page's origins only", () => { + const remote = "https://windmill.example.com/"; + expect(isAllowedDevPageOrigin("https://windmill.example.com", remote)).toBe(true); + // The --proxy-port page and a locally run frontend are on this machine. + expect(isAllowedDevPageOrigin("http://localhost:3002", remote)).toBe(true); + expect(isAllowedDevPageOrigin("http://127.0.0.1:3000", remote)).toBe(true); + // Non-browser clients send no Origin. + expect(isAllowedDevPageOrigin(undefined, remote)).toBe(true); + + expect(isAllowedDevPageOrigin("https://other.example", remote)).toBe(false); + expect(isAllowedDevPageOrigin("http://windmill.example.com", remote)).toBe(false); + expect(isAllowedDevPageOrigin("https://windmill.example.com.other.example", remote)).toBe(false); + expect(isAllowedDevPageOrigin("null", remote)).toBe(false); +}); + +test("a Host that DNS could re-point is refused on a loopback bind", () => { + expect(isAllowedHostHeader("localhost:3001", "127.0.0.1")).toBe(true); + expect(isAllowedHostHeader("127.0.0.1:3001", "127.0.0.1")).toBe(true); + expect(isAllowedHostHeader("[::1]:3001", "localhost")).toBe(true); + expect(isAllowedHostHeader("192.168.1.5:4000", "localhost")).toBe(true); + expect(isAllowedHostHeader("other.example:3001", "127.0.0.1")).toBe(false); + expect(isAllowedHostHeader(undefined, "127.0.0.1")).toBe(false); + // An explicit --host is a name the developer chose. + expect(isAllowedHostHeader("devbox:4000", "devbox")).toBe(true); + // A wildcard bind is reachable under any name the developer exposed. + expect(isAllowedHostHeader("devbox.lan:3001", "0.0.0.0")).toBe(true); +}); + +test("message paths stay inside the checkout", () => { + const base = path.resolve("/tmp/checkout"); + expect(isWithinFolder(base, path.join(base, "f/foo.flow/a.ts"))).toBe(true); + expect(isWithinFolder(base, base)).toBe(true); + expect(isWithinFolder(base, path.join(base, "f/../../ops/deploy"))).toBe(false); + expect(isWithinFolder(base, "/home/someone/.bashrc")).toBe(false); + expect(isWithinFolder(base, "/tmp/checkout-other/a.ts")).toBe(false); +}); + +test("only a UUID is taken as a job id", () => { + expect(isJobId("0190c5e4-6b2a-7c3d-8e9f-0123456789ab")).toBe(true); + expect(isJobId("../../variables/list")).toBe(false); + expect(isJobId("0190c5e4-6b2a-7c3d-8e9f-0123456789ab/../x")).toBe(false); + expect(isJobId(undefined)).toBe(false); +}); + +test("wmill dev binds only addresses the dev page reaches on localhost", () => { + for (const h of ["127.0.0.1", "localhost", "::1", "0.0.0.0", "::"]) { + expect(bindsLocalhost(h)).toBe(true); + } + for (const h of ["127.0.0.2", "192.168.1.10", "example.com"]) { + expect(bindsLocalhost(h)).toBe(false); + } +}); diff --git a/cli/test/inline_path_within_unit.test.ts b/cli/test/inline_path_within_unit.test.ts new file mode 100644 index 0000000000..1cd7834e8a --- /dev/null +++ b/cli/test/inline_path_within_unit.test.ts @@ -0,0 +1,64 @@ +import { afterAll, describe, expect, test } from "bun:test"; +import { + mkdirSync, + mkdtempSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { inlinePathWithin, readInlinePathSync } from "../src/utils/utils.ts"; +import { validateInlineResourcePointer } from "../src/commands/resource/resource.ts"; + +const scratch = mkdtempSync(join(tmpdir(), "wmill-inline-")); +const root = join(scratch, "repo"); +const outside = join(scratch, "outside.txt"); +mkdirSync(join(root, "f", "res"), { recursive: true }); +writeFileSync(join(root, "f", "res", "conf.resource.file.ini"), "inside"); +writeFileSync(outside, "outside"); +symlinkSync(outside, join(root, "f", "res", "link.resource.file.ini")); + +afterAll(() => rmSync(scratch, { recursive: true, force: true })); + +describe("inline references", () => { + test("keeps inline references inside the sync directory", () => { + expect(readInlinePathSync("f/res/conf.resource.file.ini", root)).toBe( + "inside", + ); + for (const ref of [ + "../outside.txt", + "f/../../outside.txt", + outside, + "f/res/link.resource.file.ini", + ]) { + expect(() => inlinePathWithin(ref, root)).toThrow(/outside/); + expect(() => readInlinePathSync(ref, root)).toThrow(/outside/); + } + }); + + test("a missing file inside the directory is left to the reader", () => { + expect(inlinePathWithin("f/res/missing.txt", root)).toBe( + join(root, "f", "res", "missing.txt"), + ); + }); + + test("a synced resource reads only its own content file", () => { + validateInlineResourcePointer("f/res/conf.resource.file.ini", "f/res/conf"); + validateInlineResourcePointer( + "f/res/conf.prod.resource.file.ini", + "f/res/conf", + "f/res/conf.prod.resource.yaml", + ); + for (const ref of [ + "f/res/other.resource.file.ini", + "f/res/conf.resource.file.", + "f/res/conf.resource.file.x/../../y", + "../.config/windmill/remotes.ndjson", + ]) { + expect(() => validateInlineResourcePointer(ref, "f/res/conf")).toThrow( + /content file must live next to it/, + ); + } + }); +}); diff --git a/cli/test/remote_key_within_folder_unit.test.ts b/cli/test/remote_key_within_folder_unit.test.ts new file mode 100644 index 0000000000..7c9b5962a4 --- /dev/null +++ b/cli/test/remote_key_within_folder_unit.test.ts @@ -0,0 +1,30 @@ +import { expect, test } from "bun:test"; +import { join } from "node:path"; +import { remoteKeyWithinFolder } from "../src/commands/sync/sync.ts"; + +const FILESET = join("f", "res", "data.fileset"); + +test("fileset keys and module names land inside their folder", () => { + expect(remoteKeyWithinFolder(FILESET, "q.sql")).toBe(join(FILESET, "q.sql")); + expect(remoteKeyWithinFolder(FILESET, "models/staging/a.sql")).toBe( + join(FILESET, "models", "staging", "a.sql"), + ); +}); + +test("fileset keys that are not plain relative paths are refused", () => { + for (const key of [ + "../cleanup.sh", + "a/../../b.sh", + "/etc/cron.d/x", + "C:/x.ts", + "a\\..\\..\\b.ts", + "a\0b", + "a//b", + "./a", + "", + ]) { + expect(() => remoteKeyWithinFolder(FILESET, key)).toThrow( + /must be a relative path/, + ); + } +}); diff --git a/cli/test/unified_generate_metadata.test.ts b/cli/test/unified_generate_metadata.test.ts index bb73e54b37..cf18ab5d88 100644 --- a/cli/test/unified_generate_metadata.test.ts +++ b/cli/test/unified_generate_metadata.test.ts @@ -595,7 +595,7 @@ describe("generate-metadata folder argument", () => { }); }); - test("non-existent folder shows up-to-date", async () => { + test("non-existent folder says nothing was found", async () => { await withTestBackend(async (backend, tempDir) => { await setupWorkspace(backend, tempDir, "nonexistent_folder_test"); @@ -609,7 +609,60 @@ describe("generate-metadata folder argument", () => { ); expect(result.code).toEqual(0); - expect(result.stdout).toContain("up-to-date"); + const output = result.stdout + result.stderr; + expect(output).toContain('No scripts, flows or apps to check under "f/does_not_exist"'); + expect(output).not.toContain("up-to-date"); + }); + }); + + test("--strict-folder-boundaries creates no metadata outside the folder", async () => { + await withTestBackend(async (backend, tempDir) => { + await setupWorkspace(backend, tempDir, "strict_missing_metadata_test"); + + await createLocalScript(tempDir, "f/panel", "edited"); + // Scripts kept without metadata on purpose, outside the folder + await mkdir(`${tempDir}/f/starbase`, { recursive: true }); + await writeFile( + `${tempDir}/f/starbase/bare.ts`, + `export async function main() {\n return 1;\n}\n`, + "utf-8" + ); + + const result = await backend.runCLICommand( + ["generate-metadata", "--yes", "f/panel", "--strict-folder-boundaries"], + tempDir, + "strict_missing_metadata_test" + ); + + expect(result.code).toEqual(0); + expect((result.stdout + result.stderr).replaceAll("\\", "/")).toContain("f/panel/edited"); + await expect(stat(`${tempDir}/f/starbase/bare.script.yaml`)).rejects.toThrow(); + await expect(stat(`${tempDir}/f/starbase/bare.script.lock`)).rejects.toThrow(); + const lockfile = await readFile(`${tempDir}/wmill-lock.yaml`, "utf-8"); + expect(lockfile).toContain("f/panel/edited"); + }); + }); + + test("folder outside the includes says it was not checked", async () => { + await withTestBackend(async (backend, tempDir) => { + await setupWorkspace(backend, tempDir, "folder_outside_includes_test"); + await writeFile(`${tempDir}/wmill.yaml`, `defaultTs: bun +includes: + - "f/starbase/**" +excludes: []`, "utf-8"); + + await createLocalScript(tempDir, "f/panel", "edited"); + + const result = await backend.runCLICommand( + ["generate-metadata", "--yes", "f/panel"], + tempDir, + "folder_outside_includes_test" + ); + + expect(result.code).toEqual(0); + const output = result.stdout + result.stderr; + expect(output).toContain('Nothing under "f/panel" was checked'); + expect(output).not.toContain("up-to-date"); }); }); }); diff --git a/cli/windmill-utils-internal/README.md b/cli/windmill-utils-internal/README.md index 2d60566621..25d75fd942 100644 --- a/cli/windmill-utils-internal/README.md +++ b/cli/windmill-utils-internal/README.md @@ -1,4 +1,4 @@ -# Windmill Utils Internal +# @windmill-labs/utils-internal Internal TypeScript utility package for Windmill development tools and scripts. @@ -32,8 +32,10 @@ npm run build ### Publishing -To publish the package: +The CLI and the frontend build from this source, so a change here needs no publish. npm only serves code outside this repo. When that needs a change, bump the version in `package.json` and `package-lock.json`: the next Windmill release publishes it (`.github/workflows/npm_on_release.yml`), and releases without a bump skip it. + +To publish without waiting for a release, as a maintainer of the npm org: ```bash ./publish.sh -``` \ No newline at end of file +``` diff --git a/cli/windmill-utils-internal/package-lock.json b/cli/windmill-utils-internal/package-lock.json index f28668938c..1c26c172c8 100644 --- a/cli/windmill-utils-internal/package-lock.json +++ b/cli/windmill-utils-internal/package-lock.json @@ -1,12 +1,12 @@ { - "name": "windmill-utils-internal", - "version": "1.8.6", + "name": "@windmill-labs/utils-internal", + "version": "1.8.7", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "windmill-utils-internal", - "version": "1.8.6", + "name": "@windmill-labs/utils-internal", + "version": "1.8.7", "license": "Apache 2.0", "devDependencies": { "@types/node": "^24.2.0", diff --git a/cli/windmill-utils-internal/package.json b/cli/windmill-utils-internal/package.json index 2b80f84f81..faa64b4133 100644 --- a/cli/windmill-utils-internal/package.json +++ b/cli/windmill-utils-internal/package.json @@ -1,6 +1,6 @@ { - "name": "windmill-utils-internal", - "version": "1.8.6", + "name": "@windmill-labs/utils-internal", + "version": "1.8.7", "description": "Internal utility functions for Windmill", "main": "dist/cjs/index.js", "module": "dist/esm/index.js", @@ -29,11 +29,19 @@ ], "author": "Ruben Fiszel", "license": "Apache 2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/windmill-labs/windmill.git", + "directory": "cli/windmill-utils-internal" + }, "devDependencies": { "@types/node": "^24.2.0", "typescript": "^5.0.0" }, "files": [ "dist/**/*" - ] + ], + "publishConfig": { + "access": "public" + } } diff --git a/cli/windmill-utils-internal/src/deploy.ts b/cli/windmill-utils-internal/src/deploy.ts index babb2f8a90..892b4ea03f 100644 --- a/cli/windmill-utils-internal/src/deploy.ts +++ b/cli/windmill-utils-internal/src/deploy.ts @@ -624,6 +624,8 @@ export async function deployItem( value: variable.value ?? "", is_secret: variable.is_secret, description: variable.description ?? "", + // No `?? []`: cleared labels read back as [], while absent ones may never have been + // copied into the fork, so defaulting them would wipe the target's. labels: variable.labels, // `null` clears; absent would keep the target's stored date. value_valid_until: variable.value_valid_until ?? null, @@ -930,6 +932,7 @@ export async function getItemValue( schema: flow.schema, value: flow.value, job_token_scopes: flow.job_token_scopes ?? null, + labels: flow.labels ?? [], }; } else if (kind === "script") { const script = await provider.getScriptByPath({ workspace, path }); @@ -941,9 +944,11 @@ export async function getItemValue( description: script.description, language: script.language, job_token_scopes: script.job_token_scopes ?? null, + labels: script.labels ?? [], }; } else if (kind === "app" || kind === "raw_app") { - return await provider.getAppByPath({ workspace, path }); + const app = await provider.getAppByPath({ workspace, path }); + return { ...app, labels: app.labels ?? [] }; } else if (kind === "variable") { const variable = await provider.getVariable({ workspace, @@ -955,6 +960,7 @@ export async function getItemValue( is_secret: variable.is_secret, description: variable.description, value_valid_until: variable.value_valid_until ?? undefined, + labels: variable.labels ?? [], }; } else if (kind === "resource") { const resource = await provider.getResource({ workspace, path }); @@ -968,6 +974,7 @@ export async function getItemValue( value, description: resource.description, resource_type: resource.resource_type, + labels: resource.labels ?? [], }; } else if (kind === "resource_type") { const rt = await provider.getResourceType({ workspace, path }); @@ -988,6 +995,7 @@ export async function getItemValue( owners: folder.owners, extra_perms: folder.extra_perms, summary: folder.summary, + labels: folder.labels ?? [], }; } else if (kind === "schedule") { // Mirror the runtime-fields-ignore set used server-side so the diff drawer diff --git a/cli/windmill-utils-internal/src/index.ts b/cli/windmill-utils-internal/src/index.ts index d23a11e8a6..827091e557 100644 --- a/cli/windmill-utils-internal/src/index.ts +++ b/cli/windmill-utils-internal/src/index.ts @@ -1,5 +1,5 @@ /** - * @fileoverview Main entry point for windmill-utils-internal package + * @fileoverview Main entry point for the @windmill-labs/utils-internal package * * This module provides utilities for handling Windmill flows, scripts, and schemas: * - Inline script extraction and replacement diff --git a/docker-compose.yml b/docker-compose.yml index d456dc6dba..48e7aeead0 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -54,6 +54,15 @@ services: environment: - DATABASE_URL=${DATABASE_URL} - MODE=server + # The proxies whose X-Forwarded-For is believed, so audit logs, login rate limits and token + # IP allowlists see the real client address. `caddy` is the service below, resolved by name. + # With a load balancer in front of Caddy, let Caddy keep its forwarding header + # (`trusted_proxies` in the Caddyfile) and add the balancer's addresses here. Behind + # Cloudflare, set TRUST_CLOUDFLARE=true and never list Cloudflare's ranges here: any + # Cloudflare customer's Worker sends from them, so they reach audit logs and rate limits only, + # and token IP allowlists see the Cloudflare edge. + - TRUSTED_PROXIES=${TRUSTED_PROXIES:-caddy} + # - TRUST_CLOUDFLARE=true depends_on: db: condition: service_healthy diff --git a/docker/RHEL8/Dockerfile b/docker/RHEL8/Dockerfile index a7eca5fbd8..c907fa3e3b 100644 --- a/docker/RHEL8/Dockerfile +++ b/docker/RHEL8/Dockerfile @@ -35,6 +35,8 @@ COPY /backend/windmill-api/build_openapi.sh /backend/windmill-api/build_openapi. COPY /system_prompts/auto-generated /system_prompts/auto-generated # The flow chat imports the chat SDK's source (svelte.config.js alias `windmill-chat`). COPY /chat-sdk/src /chat-sdk/src +# Shared with the CLI (svelte.config.js alias `windmill-utils-internal`). +COPY /cli/windmill-utils-internal/src /cli/windmill-utils-internal/src RUN cd /backend/windmill-api && . ./build_openapi.sh COPY /backend/parsers/windmill-parser-wasm/pkg/ /backend/parsers/windmill-parser-wasm/pkg/ diff --git a/docker/RHEL9/Dockerfile b/docker/RHEL9/Dockerfile index cc972884d8..afed13e20c 100644 --- a/docker/RHEL9/Dockerfile +++ b/docker/RHEL9/Dockerfile @@ -35,6 +35,8 @@ COPY /backend/windmill-api/build_openapi.sh /backend/windmill-api/build_openapi. COPY /system_prompts/auto-generated /system_prompts/auto-generated # The flow chat imports the chat SDK's source (svelte.config.js alias `windmill-chat`). COPY /chat-sdk/src /chat-sdk/src +# Shared with the CLI (svelte.config.js alias `windmill-utils-internal`). +COPY /cli/windmill-utils-internal/src /cli/windmill-utils-internal/src RUN cd /backend/windmill-api && . ./build_openapi.sh COPY /backend/parsers/windmill-parser-wasm/pkg/ /backend/parsers/windmill-parser-wasm/pkg/ diff --git a/docs/auth-surface.md b/docs/auth-surface.md index 90157c4a31..4355d61874 100644 --- a/docs/auth-surface.md +++ b/docs/auth-surface.md @@ -5,6 +5,16 @@ Symbols, not line numbers, are cited: they drift less. - **Credential precedence** (`windmill-api-auth/src/auth.rs` `extract_token`): `Authorization: Bearer` → `token` cookie → `?token=` query param. A URL with `?token=` is a credential on every route, but an existing cookie silently wins over it. +- **The cookie counts only on requests from the instance's own origin** + (`windmill-api-auth/src/request_site.rs`). On a non-GET/HEAD/OPTIONS request `extract_token` + sets the cookie aside unless `Sec-Fetch-Site` is `same-origin` or `none`; without that header + (plain http, old Safari), `Origin`, then `Referer`, must name the request's `Host`, + `X-Forwarded-Host` or `BASE_URL` host (ports ignored); with none of the three the request is + not from a browser page and keeps the cookie. A set-aside request authenticates as if it had + no cookie: on its `?token=` if any, else anonymously on optional-auth routes, else 403. GETs + are not covered except by `CrossSiteGetGuard` (Hub script runs). `same-site` is foreign: the + `SameSite=Lax` cookie reaches every sibling subdomain. `SESSION_COOKIE_TRUSTED_ORIGINS` + (comma-separated hosts or origins, `*` for all) admits named sites for both checks. - **`AUTH_CACHE`** caches a token's identity for 120 s. Deleting a token row purges it only for some rows: the delete trigger (`notify_token_invalidation`, last replaced in `migrations/20261106141303_mcp_oauth_token_delete_revokes_grant.up.sql`) notifies every @@ -25,6 +35,40 @@ Symbols, not line numbers, are cited: they drift less. access-token row, then its grant, the order the trigger also follows. A new path that writes a user's tokens and may revoke must lock that row first too. `leave_workspace` deletes no tokens and revokes nothing; `leave_instance` deletes every token of the account, as `delete_user` does. +- **Two-factor (TOTP) guards `POST /auth/login` only** (`windmill-api-users/src/totp_ee.rs`, + with a stub in `totp_oss.rs`; a build without `enterprise` allows it for one user). The + password is checked first, so "Two-factor code required" tells only someone who knows the + password that a code is needed. Every other way into a session skips it on purpose: OAuth and + SAML (the provider owns the second factor), login links (minted by a superadmin, who can reset + the second factor anyway, and never for a superadmin or devops account), and `GET /users/refresh_token` (a session already exists). + Authenticator codes are single-use (`totp_last_step`), and so are the ten recovery codes, stored + as salted argon2 hashes (a code carries about 52 bits, too few for a plain digest) and are + accepted wherever a code is. Wrong codes are capped per account at 5 a minute on the + `password` row, so the cap holds across servers; the caller commits the count even when it + refuses the code. Without that cap, a known password leaves a 6-digit code as the only barrier. + Enrolling (`setup`) asks for the password again, so a stolen session cannot add its own + authenticator and lock the owner out of password login. A superadmin removes a lost second + factor with `POST /users/totp/reset/{user}`. The secret is + encrypted under the `admins` workspace key, and rotating that key re-encrypts it + (`set_encryption_key`); a secret left under an old key locks its user out. The global user + export leaves it out, as its files end up in git: an overwrite keeps the second factor of every + account it reinstates, and a push to another instance arrives without one. + The `require_totp` instance setting (enterprise only, `totp::required`) makes a password login + without a second factor answer "Two-factor setup required" once the password matched. The + account then enrolls before it has any session, through `POST /auth/login/totp/setup` and + `/auth/login/totp/enable`, which take the password again on each call; `enable` turns the + factor on and mints the session in one transaction, so no session exists without it. While + required, `disable` is refused; a superadmin `reset` is not, and sends the user back through + enrollment. Sessions minted before the setting was turned on stay valid until they expire, + but `refresh_token` no longer renews one for an account without a second factor, so it ends + within `MAX_SESSION_VALIDITY_SECONDS` and the next login goes through the setup. The app + warns in its last 30 minutes, and enrolling from the settings restores renewal. + Until an account enrolls, its password is its only factor: whoever logs in with it first + enrolls their own authenticator, so a password already stolen is not protected, and the owner + needs a superadmin `reset` to recover. Turning the factor on (in settings or at login), off, + regenerating its recovery codes and a superadmin `reset` each email the account's owner when + SMTP is set up (`totp_ee::notify`), after the change has committed, so a change made with a + stolen password or session reaches the owner. - **Sessions** are `token` rows with `label='session'` plus the HttpOnly `token` cookie, minted only by `create_session_token` (`windmill-api-users/src/users.rs`). `GET /api/users/refresh_token` mints one for any non-job token but returns plain text, no redirect. @@ -36,6 +80,19 @@ Symbols, not line numbers, are cited: they drift less. expiry or another login changes or drops it. A session revoked server-side keeps its hint, so until `whoami` answers that browser still renders as its own last user. - **`tokens/impersonate`** (superadmin) returns a multi-use token and sets no cookie. +- **Token risk flags** (rights the token was minted with and no scope narrows, not bound to a + workspace, no expiration, unused 90 days) are computed once, by the `token_risk` view, which also + marks the tokens the server expires or renews on its own (`self_managed`, no flags). The user's + `tokens/list` and `tokens/risk_counts` and the superadmin review read it: its counts + (`tokens/risk_counts_as_super_admin`) in CE, its list (`tokens/list_as_super_admin`, cursor-paged + on `(last_used_at, token_prefix)`) and `tokens/delete_as_super_admin/{email}/{prefix}` in EE + (`users_ee.rs`); `frontend/src/lib/components/settings/tokenRisks.ts` only words the flags. +- **`GET /api/tokens/introspect`** describes the credential presenting it, never one named in + the request, and resolves it in the handler rather than through `ApiAuthed`: the route layer + would refuse a scoped token there, and a workspace-bound one resolves on no global route. Its + route verdict is `check_route_layer` (`windmill-api-auth/src/auth.rs`), the function the auth + extractor runs, plus the runnable scope of the run-by-path endpoints (`run_by_path_scope`); a + handler that checks a scope of its own and is missing there gets an over-reported "allowed". - **`max_token_expiration_days`** caps `POST /users/tokens/create` and `tokens/impersonate`, by shortening the stored expiration (`cap_token_expiration`), never by refusing: `wmill user create-token` and the editor's language-server token pick a lifetime without reading the @@ -69,12 +126,49 @@ Symbols, not line numbers, are cited: they drift less. `ephemeral-` prefix needs no other change (keep it clear of `is_server_minted_label` if minted through `tokens/create`); a new prefix also goes into the SQL and Svelte mirrors that function's doc lists. -- **A token's `super_admin` column is what lets it into a workspace its owner is not a member - of**, and makes a workspace-less MCP token list every workspace. `create_token_internal` copies - it from `password` for every token except an MCP one (an `mcp:` scope), which carries it only - when the request sets `super_admin`; the MCP OAuth approve stores the same request on its code - and refresh rows, and each exchange re-checks `password`. A new path minting an MCP token must - ask the same question, or it reaches a different set of workspaces than the other two. +- **A token carries its owner's superadmin and workspace admin rights only when minted with + them** (`token.super_admin`, `token.admin`). `super_admin` lets a token into a workspace its + owner is not a member of and makes a workspace-less MCP token list every workspace; on any row + but a session it also decides the superadmin routes, which otherwise key off the account's + email: the auth lookup sets `ApiAuthed::super_admin_withheld`, read by `require_super_admin`, + `is_super_admin_authed` and `require_devops_role`, and `admin = false` caps `is_admin` there + (`admin_withheld`, also read by the cross-workspace `usr.is_admin` checks). `POST + /users/tokens/create` and `tokens/impersonate` withhold both unless the request sets them; + `create_token_internal` called directly (server-side mints) inherits them from the owner, + except for an MCP token's superadmin. Either way a token never gets rights the minting + credential withholds, and `GET /users/refresh_token` refuses one that withholds rights the + account holds, since a session carries them all. A job started by such a token runs with its + capped `is_admin` (and a `$WM_TOKEN` cannot reach `tokens/create`); but what the token deploys + or schedules runs later as its owner (`fetch_authed_from_permissioned_as`), with every right of + the account, as with scoped tokens. Losing superadmin follows the owner without + help from the caller: the deferred trigger `password_superadmin_demote_tokens` clears the column + on every token of an address that, at commit, no longer has a superadmin `password` row + (demotion, deletion, an import's delete-and-reinsert), and evicts each through + `notify_token_invalidation`. An email change does not fire it, since SCIM's rename leaves the + tokens under the old address. A promotion grants it to no existing token. The MCP OAuth approve + stores the `super_admin` request on its code and refresh rows, and each exchange re-checks + `password`. A new path minting a token must ask the same questions, or it reaches a different + set of workspaces than the others. What withholding admin costs is reported, not enforced, + in `windmill-api/src/admin_reliance.rs`: `POST /tokens/admin_reliance` lists what a token of + given scopes reaches only through the caller's admin role (the token forms and the inspector + show it), and `hint_withheld_admin` appends a hint to a workspace route's refusal when the + credential withholds admin its owner holds there. A new admin-only action belongs in its + `ADMIN_ONLY` list. +- **Editing a token widens it only as far as the caller could mint it** + (`tokens/update_scopes`, `tokens/update_limits` for expiration and `allowed_ips`). Narrowing is + always allowed; a change that widens any of them (scopes outside the stored ones, a later or + removed expiration, networks outside the stored list or none) must leave a token + `ensure_grant_within_caller` accepts: scopes within the caller's, no superadmin unless the caller + is unscoped and carries it, no admin the caller withholds, networks within the caller's. A later + expiration goes through `cap_token_expiration`, and changing it re-registers the expiry warning. + Only user tokens (`is_user_token`) take limit edits, and only they or an MCP OAuth sign-in widen + scopes: a system token is minted narrow for wherever it is handed. Every job token is refused, + since `$WM_TOKEN` is unscoped and narrowing breaks whatever holds the token. +- **A token's history replays from the audit log.** `users.token.create` and `users.impersonate` + record everything the row holds (`TokenAuditGrant`), and each edit records its fields before and + after (`update_limits` also which fields were asked for, and the requested expiration when the + ceiling shortened it). A new token path or column must keep both, or the chain breaks. Not + audited: the superadmin-demotion trigger, the expired-token sweep, and refused edits. - **Every superadmin route refuses a job token**: `require_super_admin` (`windmill-api-auth/src/lib.rs`) errors on `authed.job_id.is_some()`. A script that needs `users/create`, `tokens/impersonate`, `set_login_type`, … must use a dedicated superadmin user @@ -164,6 +258,18 @@ Symbols, not line numbers, are cited: they drift less. reset require `login_type = 'password'`; `set_password` also accepts `pending_oauth` and turns the account into a `password` one in the same statement (an account created ahead of its owner gets its first credential that way, or through the OAuth claim below). +- **`RequireSso` protection rule** (workspace-level, `check_new_member_sso` / + `check_password_login_allowed` in `windmill-common/src/workspaces.rs`): a `password` account + held by it (not a service account, not a bypasser by username or group, admins included) cannot + join the workspace, and no member it holds can become a `password` account. It gates both + transitions, never sign-in: password members already in the workspace keep logging in, which only + the instance's `disable_password_login` stops. A new path that seats a member or writes + `login_type = 'password'` (or a password on a `pending_oauth` account) must call the matching + check in the transaction that writes. The two checks take no lock, so a join and a password + switch of the same account at the same instant can both pass; the automatic joins (domain auto-add and auto-invite, + instance groups) skip the user instead of failing, and a git sync pull into a fork fails rather + than seat a held sync identity. The + superadmin instance import (`POST /users/overwrite`) restores accounts as given, unchecked. - **Login links** (`login_link` table, `POST /users/login_links` superadmin-only, `GET /auth/login_link/{token}` unauthenticated): single-use, ≤15 min, a session cookie and a 302 to a same-origin `rd`. `require_login_type` on the mint refuses (409) an account whose @@ -220,3 +326,101 @@ Symbols, not line numbers, are cited: they drift less. profile routes are cloud-gated; for the rest, cloud only adds quotas. - **`CREATE_WORKSPACE_REQUIRE_SUPERADMIN`** defaults to `true` when unset; only the literal `"true"` enables it when set. +- **The client IP** (`windmill-common/src/client_ip.rs`) is the TCP peer unless that peer is a + trusted proxy. With `TRUSTED_PROXIES` unset, loopback and the private ranges are trusted, where + the ingress or reverse proxy of a Helm or compose deployment sits, so audit entries, the login + rate limit and token IP allowlists all see client addresses with nothing configured. The cost: + any host on the private network, a job's container included, can name its own client address, + an allowlisted one included. A leaked token stays restricted for an outsider, whose requests + come through the ingress, but not for someone who can run a job or reach the network. **This is + an accepted risk, decided on purpose for zero-configuration Helm and compose installs; do not + report the default itself as a vulnerability.** What would be a finding is a change that widens + it: a public range trusted by default, forwarding headers believed from a peer outside the + trusted list, or Cloudflare reaching token allowlists. A startup warning, the Client IP settings + page and the token dialog point to + `TRUSTED_PROXIES`, and audit entries keep `peer_ip` (when it differs) and `forwarded_for` (the + raw header) so a named address is told apart. Excluding the addresses Windmill's own workers + run jobs from cannot close it: NAT, interfaces added after startup and standalone mode leave + addresses no worker can know it is seen from. An explicit `TRUSTED_PROXIES` replaces the default: + comma-separated IPs, CIDRs, `private`, and hostnames (re-resolved every 15s, a name that does not + resolve trusts nothing; the compose template sets `caddy`); empty or `none` trusts nothing. + Each of the three variables is also a global setting (`trusted_proxies`, `trust_cloudflare`, + `client_ip_header`) edited on the Client IP page; a variable that is set wins over its setting + for good, and the page shows it read-only. A stored list is checked on write and again on load: + a `/0`, a range overlapping Cloudflare's (that is what `trust_cloudflare` is for) and an + unreadable entry are refused, not dropped silently. The trust is one `ArcSwap` rebuilt whole by + `client_ip::reload` on `notify_global_setting_change` in every process, and right after the + write on the server that took it; a `MODE=mcp` process, which joins no monitor loop, polls the + three settings at the same interval instead. A hostname kept across a swap keeps its resolved + addresses. + A wrong value cannot lock a superadmin out of the page: sessions never carry `allowed_ips`, and + the per-IP login limit, off on self-hosted unless `LOGIN_RATE_LIMIT_PER_IP` is set, is per + minute; the variables still override a stored value. + Two views differ only by Cloudflare: *enforced* (`ClientIp`, `client_ip_of`, `/api/client_ip`, + read by token allowlists) and *attributed* (`AttributedClientIp`, `request_origin.rs`, read by + audit entries and the login rate limit). `TRUST_CLOUDFLARE=true` adds Cloudflare's published + ranges, embedded in the code, to the attributed view only. Past a Cloudflare hop the client is + `CF-Connecting-IP`, never the rest of `X-Forwarded-For`, since every Cloudflare customer's Worker + sends from those ranges with headers it writes. Cloudflare overwrites `CF-Connecting-IP` only on + requests to a Cloudflare zone: a Worker calling an origin directly (a DNS-only hostname, the load + balancer's own address) sets it freely. So the source range cannot prove the request came + through the instance's own zone, and token allowlists behind Cloudflare see the edge. + Behind a trusted peer, `X-Forwarded-For` is read from the right up to the first untrusted hop, + or, with `CLIENT_IP_HEADER` set, only that header (`CloudFront-Viewer-Address`, + `CF-Connecting-IP`, an nginx `X-Real-IP`). `X-Real-IP` is never read implicitly: Caddy and most + ingresses pass a client's own through. A CDN in front of the load balancer (CloudFront on + app.windmill.dev) needs `CLIENT_IP_HEADER` or its ranges in `TRUSTED_PROXIES`, or its edge + address is the client. A peer sending forwarding headers that are not believed is logged once + an hour (at most 20 such warnings an hour per process) and listed on the instance settings' + Client IP page (`/settings/client_ip_diagnostics`, per server process). Only the main API server + carries the peer: a router called without connect info (tests, internal dispatch) + sees `None`, and per-IP decisions skip or refuse it. A process that is neither a server, an MCP + server nor an indexer (a worker, whose API its own jobs call over loopback) believes no + forwarding header (`serve_local_jobs_only`): through loopback's trust a job could otherwise name + any address, an allowlisted one included. A standalone process, server and worker in one, cannot + tell its jobs from a proxy on its host, both being loopback. +- **`token.allowed_ips`** is EE. A CE build drops a stored list when it loads the token, so it + neither checks the list nor passes it on, and refuses a request that sets one. An EE build + keeps enforcing stored lists when its license lapses; only setting a new one needs a valid + license. The rest of this bullet describes an EE build. The column (`cidr[]`, `NULL` = + anywhere) restricts where a token row may be + used. `AuthCache::get_opt_job_authed` takes the request's client IP and refuses the token + outside its networks, or when the IP is unknown, so every path that resolves a request's + token passes that request's `ClientIp` (MCP's multi-workspace mode carries it in + `McpToken`). The list rides on the cached `ApiAuthed`, checked per request, never folded + into the cache entry. A restricted token cannot lift its restriction: every mint from the + caller's identity holds the new row within the caller's networks (the caller's list when + none is asked for). That is `create_token_internal` (`tokens/create`, app SDK and embed + tokens, native trigger webhook tokens, which then only work from those networks), + `tokens/impersonate` and service-account impersonation. `refresh_token`, the MCP OAuth + approve and `login_links` refuse a restricted caller, since what they lead to is a session + with no restriction. Not inherited, by design: a job's `WM_TOKEN` (a JWT; starting the job + already passed the check) and JWTs the server mints for its own loopback calls. +- **The instance IP allowlist** (`instance_ip_allowlist` setting, EE, `instance_ip_allowlist_ee.rs`) + refuses an `/api/` request before routing and authentication when its *enforced* client IP is + not listed; static assets and `/.well-known/` are not checked. Never the attributed view: behind + Cloudflare it sees the edge, and only Cloudflare Access or authenticated origin pulls restrict + an origin there. It may be in force only under named trusted proxies none of which covers a whole + private block (`ClientIpSettings::trust_is_explicit`: `private`, `10.0.0.0/8` or wider are refused, + and a client IP header alone does not count): every host of a trusted network names its own address. Every write + of the list or of the trust settings, per key, bulk or the declarative sync, goes through + `write_checked`: in one transaction holding an advisory lock, on one connection, it reads what is + stored, resolves the trust the write would put in force (`client_ip::settings_with`), refuses a + result that leaves the writing request's own address out under that trust (unless the list always + passes that request), and writes. The Client IP page saves each key as its own request, and two + writes checked apart would each be checked against the other's old value. + Turning the list off is always allowed; the license is checked only when the list is written, a + lapsed license keeps a stored list enforced, and a CE build ignores one. Always passing: requests + with no connect info (in-process dispatch), a worker process's own API, a loopback peer or trusted + proxy sending on its own behalf (`is_own_request`: no forwarding header it would read; a relayed + request is judged on the address it resolves to, since an unreadable header falls back to the + proxy's), and a request whose bearer is a valid job JWT (`job_id` set), which is how jobs reach + `BASE_INTERNAL_URL` from addresses no server can know; a job token proves no more than running + code on a worker, which already reaches the API. Everything else outside the list passes only + through a named exemption (webhooks, which native trigger deliveries call too; HTTP routes; + GitHub/GitLab webhooks, GCP/Azure pushes and Slack/Teams callbacks; public apps, with + `ee_license` but not `users/whoami`; health; the agent worker protocol, its routes named one by + one so the superadmin ones beside them stay behind the list) or a listed path prefix, matched on whole + segments, never on the query. Recovery: `INSTANCE_IP_ALLOWLIST_DISABLED=true` and a restart, or + setting `enabled` to false in `global_settings`, which every server, MCP ones included, reloads + within seconds. diff --git a/docs/feature-telemetry.md b/docs/feature-telemetry.md index ed2ca255e1..7b011ca59e 100644 --- a/docs/feature-telemetry.md +++ b/docs/feature-telemetry.md @@ -4,14 +4,14 @@ 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 111 registered actions across forty-three features (`access_view`, `ai_session`, `ai_chat`, +It currently carries 113 registered actions across forty-four features (`access_view`, `ai_session`, `ai_chat`, `autoscaling_diagnostics`, `code_mode`, `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`, `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`, -`external_secret_ref`, `anthropic_federation`, `vertex_workload_identity`, `deployment_request`, `fork_roles`, `git_sync_review`, `workspace_webhook`). Nearly all of the +`external_secret_ref`, `anthropic_federation`, `vertex_workload_identity`, `deployment_request`, `fork_roles`, `git_sync_review`, `workspace_webhook`, `instance_ip_allowlist`). 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/package-lock.json b/frontend/package-lock.json index 1e666a45a5..af68a3651e 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/components", - "version": "1.884.1", + "version": "1.894.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/components", - "version": "1.884.1", + "version": "1.894.1", "hasInstallScript": true, "license": "AGPL-3.0", "dependencies": { @@ -96,6 +96,7 @@ "tailwind-merge": "^1.13.2", "unified": "^11.0.5", "unist-util-visit": "^5.0.0", + "uqr": "^0.1.3", "vscode": "npm:@codingame/monaco-vscode-extension-api@=25.0.0", "vscode-languageclient": "~9.0.1", "vscode-uri": "~3.1.0", @@ -115,7 +116,6 @@ "windmill-parser-wasm-wac": "1.830.0", "windmill-parser-wasm-yaml": "1.770.0", "windmill-sql-datatype-parser-wasm": "1.512.0", - "windmill-utils-internal": "1.8.6", "xterm": "^5.3.0", "xterm-readline": "^1.1.2", "y-monaco": "^0.1.4", @@ -13446,6 +13446,12 @@ "browserslist": ">= 4.21.0" } }, + "node_modules/uqr": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/uqr/-/uqr-0.1.3.tgz", + "integrity": "sha512-0rjE8iEJe4YmT9TOhwsZtqCMRLc5DXZUI2UEYUUg63ikBkqqE5EYWaI0etFe/5KUcmcYwLih2RND1kq+hrUJXA==", + "license": "MIT" + }, "node_modules/uri-js": { "version": "4.4.1", "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", @@ -14140,12 +14146,6 @@ "resolved": "https://registry.npmjs.org/windmill-sql-datatype-parser-wasm/-/windmill-sql-datatype-parser-wasm-1.512.0.tgz", "integrity": "sha512-uHNL8F72/Tf96xF3hOHnPDjkEyqXw7fNjcPJiUhth9sTQkcwUIoJMOdwm8/cs+j9kKVRJ4tgNYMHEBLylazp6g==" }, - "node_modules/windmill-utils-internal": { - "version": "1.8.6", - "resolved": "https://registry.npmjs.org/windmill-utils-internal/-/windmill-utils-internal-1.8.6.tgz", - "integrity": "sha512-jzHhEZ3xSBf90zektXaAIhAu9wLo5RMtYshvjg5if8jjEJvWENd+WQzEbod8Sr+SzMUbmmF4ArefqN15f2XtHw==", - "license": "Apache 2.0" - }, "node_modules/wordwrap": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", diff --git a/frontend/package.json b/frontend/package.json index 465ca8d47e..df9dc37179 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@windmill-labs/components", - "version": "1.884.1", + "version": "1.894.1", "scripts": { "dev": "vite dev", "dev:ui-builder": "mv static/ui_builder static/ui_builder.dev-disabled 2>/dev/null || true ; trap 'mv static/ui_builder.dev-disabled static/ui_builder 2>/dev/null || true' EXIT ; vite dev", @@ -15,8 +15,8 @@ "format:check": "prettier --ignore-path .gitignore --check --plugin-search-dir=. .", "format": "prettier --ignore-path .gitignore --write --plugin-search-dir=. .", "package": "svelte-package -o package && node scripts/package-system-prompts.js && node scripts/fix-svelte-module-imports.js", - "generate-backend-client": "openapi-ts --input ../backend/windmill-api/openapi.yaml --output ./src/lib/gen --useOptions --enums javascript --format false", - "generate-backend-client-mac": "openapi-ts --input ../backend/windmill-api/openapi.yaml --output ./src/lib/gen --useOptions --enums javascript", + "generate-backend-client": "openapi-ts --input ../backend/windmill-api/openapi.yaml --output ./src/lib/gen --request ./scripts/openapi-ts-request.ts --useOptions --enums javascript --format false", + "generate-backend-client-mac": "openapi-ts --input ../backend/windmill-api/openapi.yaml --output ./src/lib/gen --request ./scripts/openapi-ts-request.ts --useOptions --enums javascript", "gen:display-catalog": "WM_GEN_DISPLAY_CATALOG=1 vitest run --project server src/lib/components/display/displayCatalogGen.test.ts", "gen:mcp-session": "WM_GEN_MCP_SESSION=1 vitest run --project server src/lib/components/copilot/chat/global/mcpSessionGen.test.ts", "pretest": "tsc --incremental -p tests/tsconfig.json", @@ -161,6 +161,7 @@ "tailwind-merge": "^1.13.2", "unified": "^11.0.5", "unist-util-visit": "^5.0.0", + "uqr": "^0.1.3", "vscode": "npm:@codingame/monaco-vscode-extension-api@=25.0.0", "vscode-languageclient": "~9.0.1", "vscode-uri": "~3.1.0", @@ -180,7 +181,6 @@ "windmill-parser-wasm-wac": "1.830.0", "windmill-parser-wasm-yaml": "1.770.0", "windmill-sql-datatype-parser-wasm": "1.512.0", - "windmill-utils-internal": "1.8.6", "xterm": "^5.3.0", "xterm-readline": "^1.1.2", "y-monaco": "^0.1.4", diff --git a/frontend/scripts/fix-svelte-module-imports.js b/frontend/scripts/fix-svelte-module-imports.js index 1a9e18bf8e..4916a959f5 100644 --- a/frontend/scripts/fix-svelte-module-imports.js +++ b/frontend/scripts/fix-svelte-module-imports.js @@ -21,7 +21,10 @@ // `chat-sdk/src/index.ts`, which escapes the package root the same way. // Compile that entry point into the package and rewrite those imports. // -// 4. `$lib/utils` from inside `utils/`: svelte-package turns it into `./`, +// 4. Utils: the `windmill-utils-internal` alias points at +// `cli/windmill-utils-internal/src`, handled like the chat SDK. +// +// 5. `$lib/utils` from inside `utils/`: svelte-package turns it into `./`, // which is the `utils/` directory (no index) rather than `utils.js`. // Point a directory specifier with no index at its sibling module. // @@ -45,32 +48,46 @@ copyFileSync(oauthConnectSrc, oauthConnectDest) const chatSdkSrc = resolve(__dirname, '..', '..', 'chat-sdk', 'src', 'index.ts') const chatSdkDest = join(packageDir, 'chat-sdk') +const utilsSrc = resolve(__dirname, '..', '..', 'cli', 'windmill-utils-internal', 'src') +const utilsDest = join(packageDir, 'utils-internal') +const utilsModules = ['deploy', 'parse/parse-schema'] + // File arguments make tsc ignore every tsconfig and emit only what the entry // point reaches, which leaves out the React and AI SDK adapters. -execFileSync( - 'npx', - [ - 'tsc', - chatSdkSrc, - '--outDir', - chatSdkDest, - '--rootDir', - dirname(chatSdkSrc), - '--declaration', - '--target', - 'ES2021', - '--module', - 'ESNext', - '--moduleResolution', - 'bundler', - '--skipLibCheck' - ], - { stdio: 'inherit', cwd: resolve(__dirname, '..') } +function compile(entries, outDir, rootDir) { + execFileSync( + 'npx', + [ + 'tsc', + ...entries, + '--outDir', + outDir, + '--rootDir', + rootDir, + '--declaration', + '--target', + 'ES2021', + '--module', + 'ESNext', + '--moduleResolution', + 'bundler', + '--skipLibCheck' + ], + { stdio: 'inherit', cwd: resolve(__dirname, '..') } + ) +} + +compile([chatSdkSrc], chatSdkDest, dirname(chatSdkSrc)) +compile( + utilsModules.map((m) => join(utilsSrc, `${m}.ts`)), + utilsDest, + utilsSrc ) const IMPORT_SPECIFIER_RE = /(\bfrom\s*|\bimport\s*\(?\s*)(['"])(\.\.?(?:\/[^'"]*)?)\2/g const OAUTH_CONNECT_RE = /^(\.\.\/)+backend\/oauth_connect\.json$/ const CHAT_SDK_RE = /^(\.\.\/)+chat-sdk\/src\/index\.ts$/ +const UTILS_RE = /^(?:\.\.\/)+cli\/windmill-utils-internal\/src\/(.+?)(?:\.ts)?$/ const DIRECTORY_RE = /(^|\/)\.\.?$|\/$/ const ALIASED_GLOB_RE = /import\.meta\.glob(?:<[^>]*>)?\(\s*\[?\s*['"]\$/ @@ -111,6 +128,12 @@ for (const file of walk(packageDir)) { rewrittenImports++ return `${prefix}${quote}${relativeSpecifier(file, join(chatSdkDest, 'index.js'))}${quote}` } + const utilsModule = specifier.match(UTILS_RE)?.[1] + if (utilsModules.includes(utilsModule)) { + changed = true + rewrittenImports++ + return `${prefix}${quote}${relativeSpecifier(file, join(utilsDest, `${utilsModule}.js`))}${quote}` + } const target = resolve(dirname(file), specifier) // Test files ride along in the output but no consumer imports them, so an escaping // import there (e.g. `../app.html?raw`) breaks nothing. diff --git a/frontend/scripts/openapi-ts-request.ts b/frontend/scripts/openapi-ts-request.ts new file mode 100644 index 0000000000..12f6a24304 --- /dev/null +++ b/frontend/scripts/openapi-ts-request.ts @@ -0,0 +1,367 @@ +// Custom request module for `openapi-ts --request`: the generated core/request.ts, except that +// getUrl encodes path parameters with encodePathParam (src/lib/apiPathParams.ts). +import { ApiError } from './ApiError' +import type { ApiRequestOptions } from './ApiRequestOptions' +import type { ApiResult } from './ApiResult' +import { CancelablePromise } from './CancelablePromise' +import type { OnCancel } from './CancelablePromise' +import type { OpenAPIConfig } from './OpenAPI' +import { encodePathParam } from '../../apiPathParams' + +export const isString = (value: unknown): value is string => { + return typeof value === 'string' +} + +export const isStringWithValue = (value: unknown): value is string => { + return isString(value) && value !== '' +} + +export const isBlob = (value: any): value is Blob => { + return value instanceof Blob +} + +export const isFormData = (value: unknown): value is FormData => { + return value instanceof FormData +} + +export const base64 = (str: string): string => { + try { + return btoa(str) + } catch (err) { + // @ts-ignore + return Buffer.from(str).toString('base64') + } +} + +export const getQueryString = (params: Record<string, unknown>): string => { + const qs: string[] = [] + + const append = (key: string, value: unknown) => { + qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`) + } + + const encodePair = (key: string, value: unknown) => { + if (value === undefined || value === null) { + return + } + + if (value instanceof Date) { + append(key, value.toISOString()) + } else if (Array.isArray(value)) { + value.forEach((v) => encodePair(key, v)) + } else if (typeof value === 'object') { + Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)) + } else { + append(key, value) + } + } + + Object.entries(params).forEach(([key, value]) => encodePair(key, value)) + + return qs.length ? `?${qs.join('&')}` : '' +} + +const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { + const path = options.url + .replace('{api-version}', config.VERSION) + .replace(/{(.*?)}/g, (substring: string, group: string) => { + if (options.path?.hasOwnProperty(group)) { + const value = String(options.path[group]) + return config.ENCODE_PATH ? config.ENCODE_PATH(value) : encodePathParam(group, value) + } + return substring + }) + + const url = config.BASE + path + return options.query ? url + getQueryString(options.query) : url +} + +export const getFormData = (options: ApiRequestOptions): FormData | undefined => { + if (options.formData) { + const formData = new FormData() + + const process = (key: string, value: unknown) => { + if (isString(value) || isBlob(value)) { + formData.append(key, value) + } else { + formData.append(key, JSON.stringify(value)) + } + } + + Object.entries(options.formData) + .filter(([, value]) => value !== undefined && value !== null) + .forEach(([key, value]) => { + if (Array.isArray(value)) { + value.forEach((v) => process(key, v)) + } else { + process(key, value) + } + }) + + return formData + } + return undefined +} + +type Resolver<T> = (options: ApiRequestOptions) => Promise<T> + +export const resolve = async <T>( + options: ApiRequestOptions, + resolver?: T | Resolver<T> +): Promise<T | undefined> => { + if (typeof resolver === 'function') { + return (resolver as Resolver<T>)(options) + } + return resolver +} + +export const getHeaders = async ( + config: OpenAPIConfig, + options: ApiRequestOptions +): Promise<Headers> => { + const [token, username, password, additionalHeaders] = await Promise.all([ + resolve(options, config.TOKEN), + resolve(options, config.USERNAME), + resolve(options, config.PASSWORD), + resolve(options, config.HEADERS) + ]) + + const headers = Object.entries({ + Accept: 'application/json', + ...additionalHeaders, + ...options.headers + }) + .filter(([, value]) => value !== undefined && value !== null) + .reduce( + (headers, [key, value]) => ({ + ...headers, + [key]: String(value) + }), + {} as Record<string, string> + ) + + if (isStringWithValue(token)) { + headers['Authorization'] = `Bearer ${token}` + } + + if (isStringWithValue(username) && isStringWithValue(password)) { + const credentials = base64(`${username}:${password}`) + headers['Authorization'] = `Basic ${credentials}` + } + + if (options.body !== undefined) { + if (options.mediaType) { + headers['Content-Type'] = options.mediaType + } else if (isBlob(options.body)) { + headers['Content-Type'] = options.body.type || 'application/octet-stream' + } else if (isString(options.body)) { + headers['Content-Type'] = 'text/plain' + } else if (!isFormData(options.body)) { + headers['Content-Type'] = 'application/json' + } + } + + return new Headers(headers) +} + +export const getRequestBody = (options: ApiRequestOptions): unknown => { + if (options.body !== undefined) { + if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { + return JSON.stringify(options.body) + } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { + return options.body + } else { + return JSON.stringify(options.body) + } + } + return undefined +} + +export const sendRequest = async ( + config: OpenAPIConfig, + options: ApiRequestOptions, + url: string, + body: any, + formData: FormData | undefined, + headers: Headers, + onCancel: OnCancel +): Promise<Response> => { + const controller = new AbortController() + + let request: RequestInit = { + headers, + body: body ?? formData, + method: options.method, + signal: controller.signal + } + + if (config.WITH_CREDENTIALS) { + request.credentials = config.CREDENTIALS + } + + for (const fn of config.interceptors.request._fns) { + request = await fn(request) + } + + onCancel(() => controller.abort()) + + return await fetch(url, request) +} + +export const getResponseHeader = ( + response: Response, + responseHeader?: string +): string | undefined => { + if (responseHeader) { + const content = response.headers.get(responseHeader) + if (isString(content)) { + return content + } + } + return undefined +} + +export const getResponseBody = async (response: Response): Promise<unknown> => { + if (response.status !== 204) { + try { + const contentType = response.headers.get('Content-Type') + if (contentType) { + const binaryTypes = [ + 'application/octet-stream', + 'application/pdf', + 'application/zip', + 'audio/', + 'image/', + 'video/' + ] + if (contentType.includes('application/json') || contentType.includes('+json')) { + return await response.json() + } else if (binaryTypes.some((type) => contentType.includes(type))) { + return await response.blob() + } else if (contentType.includes('multipart/form-data')) { + return await response.formData() + } else if (contentType.includes('text/')) { + return await response.text() + } + } + } catch (error) { + console.error(error) + } + } + return undefined +} + +export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { + const errors: Record<number, string> = { + 400: 'Bad Request', + 401: 'Unauthorized', + 402: 'Payment Required', + 403: 'Forbidden', + 404: 'Not Found', + 405: 'Method Not Allowed', + 406: 'Not Acceptable', + 407: 'Proxy Authentication Required', + 408: 'Request Timeout', + 409: 'Conflict', + 410: 'Gone', + 411: 'Length Required', + 412: 'Precondition Failed', + 413: 'Payload Too Large', + 414: 'URI Too Long', + 415: 'Unsupported Media Type', + 416: 'Range Not Satisfiable', + 417: 'Expectation Failed', + 418: 'Im a teapot', + 421: 'Misdirected Request', + 422: 'Unprocessable Content', + 423: 'Locked', + 424: 'Failed Dependency', + 425: 'Too Early', + 426: 'Upgrade Required', + 428: 'Precondition Required', + 429: 'Too Many Requests', + 431: 'Request Header Fields Too Large', + 451: 'Unavailable For Legal Reasons', + 500: 'Internal Server Error', + 501: 'Not Implemented', + 502: 'Bad Gateway', + 503: 'Service Unavailable', + 504: 'Gateway Timeout', + 505: 'HTTP Version Not Supported', + 506: 'Variant Also Negotiates', + 507: 'Insufficient Storage', + 508: 'Loop Detected', + 510: 'Not Extended', + 511: 'Network Authentication Required', + ...options.errors + } + + const error = errors[result.status] + if (error) { + throw new ApiError(options, result, error) + } + + if (!result.ok) { + const errorStatus = result.status ?? 'unknown' + const errorStatusText = result.statusText ?? 'unknown' + const errorBody = (() => { + try { + return JSON.stringify(result.body, null, 2) + } catch (e) { + return undefined + } + })() + + throw new ApiError( + options, + result, + `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` + ) + } +} + +/** + * Request method + * @param config The OpenAPI configuration object + * @param options The request options from the service + * @returns CancelablePromise<T> + * @throws ApiError + */ +export const request = <T>( + config: OpenAPIConfig, + options: ApiRequestOptions +): CancelablePromise<T> => { + return new CancelablePromise(async (resolve, reject, onCancel) => { + try { + const url = getUrl(config, options) + const formData = getFormData(options) + const body = getRequestBody(options) + const headers = await getHeaders(config, options) + + if (!onCancel.isCancelled) { + let response = await sendRequest(config, options, url, body, formData, headers, onCancel) + + for (const fn of config.interceptors.response._fns) { + response = await fn(response) + } + + const responseBody = await getResponseBody(response) + const responseHeader = getResponseHeader(response, options.responseHeader) + + const result: ApiResult = { + url, + ok: response.ok, + status: response.status, + statusText: response.statusText, + body: responseHeader ?? responseBody + } + + catchErrorCodes(options, result) + + resolve(result.body) + } + } catch (error) { + reject(error) + } + }) +} diff --git a/frontend/scripts/ui_builder_artifact.json b/frontend/scripts/ui_builder_artifact.json index 1194fe79df..56b749d22e 100644 --- a/frontend/scripts/ui_builder_artifact.json +++ b/frontend/scripts/ui_builder_artifact.json @@ -1,5 +1,5 @@ { "baseUrl": "https://pub-06154ed168a24e73a86ab84db6bf15d8.r2.dev", - "version": "5ae35e6", - "sha256": "cdc948ce65b3ed0befbbfab7c816f2db63ae9207bbd85653d3484516c7ac3238" + "version": "f9da2f8", + "sha256": "fec1b1536fa0f97759314337d79b1f64bd0f5fb6d5e8aee3d5e2a2abb247ca8f" } diff --git a/frontend/src/app.html b/frontend/src/app.html index 29d55331c3..385b927b18 100644 --- a/frontend/src/app.html +++ b/frontend/src/app.html @@ -159,6 +159,12 @@ var pub = /^\/public\/([^/]+)\/([^/]+)\/?$/.exec(path) var custom = /^\/a\/(.+?)\/?$/.exec(path) if (!pub && !custom && !/^\/public\//.test(path)) return + // fetch() resolves encoded dot segments and separators, which would take these + // URLs outside their route; such paths are left to the page, which refuses them. + if (/%2e|%2f|%5c|\\/i.test(path)) { + pub = null + custom = null + } // Dark as PublicApp decides it, painted before any stylesheet so that a dark app // does not load over a white page. var dark = false diff --git a/frontend/src/lib/aiStore.ts b/frontend/src/lib/aiStore.ts index aaf5c2d992..70c0c6bd6a 100644 --- a/frontend/src/lib/aiStore.ts +++ b/frontend/src/lib/aiStore.ts @@ -15,10 +15,16 @@ import { WorkspaceService } from './gen' import { + AI_REVIEW_MODEL_SETTING_NAME, + AI_REVIEW_PROVIDER_SETTING_NAME, + AI_REVIEW_REASONING_SETTING_NAME, aiUserDisabled, COPILOT_SESSION_MODEL_SETTING_NAME, COPILOT_SESSION_PROVIDER_SETTING_NAME, - COPILOT_SESSION_REASONING_SETTING_NAME + COPILOT_SESSION_REASONING_SETTING_NAME, + SCRIPT_GEN_MODEL_SETTING_NAME, + SCRIPT_GEN_PROVIDER_SETTING_NAME, + SCRIPT_GEN_REASONING_SETTING_NAME } from './stores' import { getLocalSetting, storeLocalSetting } from './utils' import { @@ -28,20 +34,51 @@ import { const USER_CUSTOM_PROMPTS_KEY = 'userCustomAIPrompts' -const sessionModel = getLocalSetting(COPILOT_SESSION_MODEL_SETTING_NAME) -const sessionProvider = getLocalSetting(COPILOT_SESSION_PROVIDER_SETTING_NAME) -const sessionReasoning = getLocalSetting(COPILOT_SESSION_REASONING_SETTING_NAME) -export const copilotSessionModel = writable<ReasoningProviderModel | undefined>( - sessionModel && sessionProvider - ? { - // Strip the deprecated /thinking suffix on read; the default effort - // (resolved later) restores reasoning for migrated selections. - model: stripLegacyThinkingSuffix(sessionModel), - provider: sessionProvider as AIProvider, - ...(sessionReasoning ? { reasoning: sessionReasoning } : {}) - } - : undefined -) +type PickSettings = { model: string; provider: string; reasoning: string } + +const LAST_PICK_SETTINGS: PickSettings = { + model: COPILOT_SESSION_MODEL_SETTING_NAME, + provider: COPILOT_SESSION_PROVIDER_SETTING_NAME, + reasoning: COPILOT_SESSION_REASONING_SETTING_NAME +} +const SCRIPT_GEN_PICK_SETTINGS: PickSettings = { + model: SCRIPT_GEN_MODEL_SETTING_NAME, + provider: SCRIPT_GEN_PROVIDER_SETTING_NAME, + reasoning: SCRIPT_GEN_REASONING_SETTING_NAME +} +const AI_REVIEW_PICK_SETTINGS: PickSettings = { + model: AI_REVIEW_MODEL_SETTING_NAME, + provider: AI_REVIEW_PROVIDER_SETTING_NAME, + reasoning: AI_REVIEW_REASONING_SETTING_NAME +} + +function readStoredPick(settings: PickSettings): ReasoningProviderModel | undefined { + const model = getLocalSetting(settings.model) + const provider = getLocalSetting(settings.provider) + const reasoning = getLocalSetting(settings.reasoning) + if (!model || !provider) return undefined + return { + // Strip the deprecated /thinking suffix on read; the default effort + // (resolved later) restores reasoning for migrated selections. + model: stripLegacyThinkingSuffix(model), + provider: provider as AIProvider, + ...(reasoning ? { reasoning } : {}) + } +} + +function storePick(settings: PickSettings, pick: ReasoningProviderModel) { + storeLocalSetting(settings.model, pick.model) + storeLocalSetting(settings.provider, pick.provider) + storeLocalSetting(settings.reasoning, pick.reasoning) +} + +export const copilotSessionModel = writable(readStoredPick(LAST_PICK_SETTINGS)) + +// Script generation's own pick, which neither follows nor sets the last pick. +export const scriptGenModel = writable(readStoredPick(SCRIPT_GEN_PICK_SETTINGS)) + +// AI review's own pick outside a session; inside one, a review starts on the session's model. +export const aiReviewModel = writable(readStoredPick(AI_REVIEW_PICK_SETTINGS)) export type CopilotInfo = { enabled: boolean @@ -304,9 +341,17 @@ export function invalidateWorkspaceCopilotInfo(workspace?: string) { * until it has one. */ export function setLastModelPick(model: ReasoningProviderModel) { copilotSessionModel.set(model) - storeLocalSetting(COPILOT_SESSION_MODEL_SETTING_NAME, model.model) - storeLocalSetting(COPILOT_SESSION_PROVIDER_SETTING_NAME, model.provider) - storeLocalSetting(COPILOT_SESSION_REASONING_SETTING_NAME, model.reasoning) + storePick(LAST_PICK_SETTINGS, model) +} + +export function setScriptGenModelPick(model: ReasoningProviderModel) { + scriptGenModel.set(model) + storePick(SCRIPT_GEN_PICK_SETTINGS, model) +} + +export function setAiReviewModelPick(model: ReasoningProviderModel) { + aiReviewModel.set(model) + storePick(AI_REVIEW_PICK_SETTINGS, model) } // Leaves copilotSessionModel alone: the pick is shared with sessions in other workspaces, which may diff --git a/frontend/src/lib/apiPathParams.test.ts b/frontend/src/lib/apiPathParams.test.ts new file mode 100644 index 0000000000..f7ae08a9df --- /dev/null +++ b/frontend/src/lib/apiPathParams.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest' +import { encodePathParam } from './apiPathParams' + +describe('encodePathParam', () => { + it('keeps slashes in path-like values', () => { + expect(encodePathParam('path', 'u/admin/my script')).toBe('u/admin/my%20script') + expect(encodePathParam('path', 'f/folder/a.b_c-d')).toBe('f/folder/a.b_c-d') + }) + + it('keeps query and fragment characters inside the segment', () => { + expect(encodePathParam('path', 'u/a/b?x=1#y')).toBe('u/a/b%3Fx=1%23y') + }) + + it('refuses dot segments, plain or percent-encoded', () => { + for (const v of ['u/../../jobs', '..', 'a/./b', 'a/%2e%2e/b', 'a/.%2E/b']) { + expect(() => encodePathParam('path', v)).toThrow() + } + expect(encodePathParam('path', 'a/...')).toBe('a/...') + }) + + it('encodes a workspace as one segment', () => { + expect(encodePathParam('workspace', 'acme-1_x')).toBe('acme-1_x') + expect(encodePathParam('workspace', 'acme/jobs/run?x=1')).toBe('acme%2Fjobs%2Frun%3Fx%3D1') + expect(() => encodePathParam('workspace', '..')).toThrow() + }) + + it('encodes percent signs so they are not decoded twice', () => { + expect(encodePathParam('path', 'a/%2e%2e%2fb')).toBe('a/%252e%252e%252fb') + }) +}) diff --git a/frontend/src/lib/apiPathParams.ts b/frontend/src/lib/apiPathParams.ts new file mode 100644 index 0000000000..735776ed9a --- /dev/null +++ b/frontend/src/lib/apiPathParams.ts @@ -0,0 +1,41 @@ +// Path parameters are filled into the API route template by the generated client +// (`scripts/openapi-ts-request.ts`). Each value must stay inside its own slot: the browser resolves +// `.`/`..` segments (also as `%2e`) and starts the query at `?` or the fragment at `#`, so an +// unchecked value would address a different route than the one the caller asked for. + +/** Parameters whose values are single identifiers and never legitimately contain `/`. */ +const SINGLE_SEGMENT_PARAMS = new Set([ + 'workspace', + 'workspace_id', + 'target_workspace_id', + 'fork_workspace_id', + 'client_name', + 'client' +]) + +export class InvalidPathParamError extends Error { + constructor(name: string) { + super(`Invalid value for path parameter "${name}"`) + this.name = 'InvalidPathParamError' + } +} + +function isDotSegment(segment: string): boolean { + return /^(\.|%2e){1,2}$/i.test(segment) +} + +function encodeSegment(segment: string): string { + return encodeURI(segment).replace(/[?#]/g, (c) => encodeURIComponent(c)) +} + +/** Encodes one path parameter value. Slashes are kept for path-like values (`u/user/script`), + * but every segment is encoded and `.`/`..` segments are refused. */ +export function encodePathParam(name: string, value: string): string { + if (SINGLE_SEGMENT_PARAMS.has(name)) { + if (isDotSegment(value)) throw new InvalidPathParamError(name) + return encodeURIComponent(value) + } + const segments = value.split('/') + if (segments.some(isDotSegment)) throw new InvalidPathParamError(name) + return segments.map(encodeSegment).join('/') +} diff --git a/frontend/src/lib/ata/apis.ts b/frontend/src/lib/ata/apis.ts index a1fb914660..66d4ec3f99 100644 --- a/frontend/src/lib/ata/apis.ts +++ b/frontend/src/lib/ata/apis.ts @@ -3,6 +3,8 @@ import pLimit from 'p-limit' import { workspaceStore } from '$lib/stores' import { get } from 'svelte/store' +import { encodePathParam } from '$lib/apiPathParams' +import { confinedSubpath } from './confinedPath' // Backend proxy fallback functions const getBackendProxyUrl = () => { @@ -10,7 +12,7 @@ const getBackendProxyUrl = () => { if (!workspace) { throw new Error('No workspace available') } - return `/api/w/${workspace}/npm_proxy` + return `/api/w/${encodePathParam('workspace', workspace)}/npm_proxy` } const backendProxyApi = async <T>(endpoint: string, resLimit: ResLimit): Promise<T | Error> => { @@ -153,11 +155,15 @@ export const getDTSFileForModuleWithVersion = ( version: string, // file comes with a prefix / file: string -) => - fromPreferredSource<string>( - () => text(`https://cdn.jsdelivr.net/npm/${moduleName}@${version}${file}`), +) => { + const confinedFile = confinedSubpath(file) + if (confinedFile === undefined) { + return Promise.resolve(new Error(`File ${file} is outside of package ${moduleName}`)) + } + return fromPreferredSource<string>( + () => text(`https://cdn.jsdelivr.net/npm/${moduleName}@${version}${confinedFile}`), async () => { - const proxyUrl = `${getBackendProxyUrl()}/file/${encodeURIComponent(moduleName)}/${encodeURIComponent(version)}${file}` + const proxyUrl = `${getBackendProxyUrl()}/file/${encodeURIComponent(moduleName)}/${encodeURIComponent(version)}${confinedFile}` const proxied = await text(proxyUrl, { credentials: 'include' }) // The callers in ata/index.ts log a fixed message and drop the value, so a cause // left inside the returned `Error` is a cause nothing ever prints. @@ -165,6 +171,7 @@ export const getDTSFileForModuleWithVersion = ( return proxied } ) +} /** * Reading the body can fail as readily as connecting, and both have to surface as a value diff --git a/frontend/src/lib/ata/confinedPath.test.ts b/frontend/src/lib/ata/confinedPath.test.ts new file mode 100644 index 0000000000..5df555d343 --- /dev/null +++ b/frontend/src/lib/ata/confinedPath.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest' +import { confinedSubpath, localImportUrl } from './confinedPath' + +const ROOT = 'http://localhost/api/scripts_u/tokened_raw/ws/tok' + +describe('localImportUrl', () => { + it('resolves relative imports next to the script', () => { + expect(localImportUrl(ROOT, 'u/admin/main', './helper')).toBe(ROOT + '/u/admin/helper') + expect(localImportUrl(ROOT, 'u/admin/main', '../other/lib')).toBe(ROOT + '/u/other/lib') + expect(localImportUrl(ROOT, 'f/folder/main', '/f/shared/util')).toBe(ROOT + '/f/shared/util') + }) + + it('refuses imports that climb above the root', () => { + expect(localImportUrl(ROOT, 'u/admin/main', '/../../../w/x/jobs')).toBeUndefined() + expect(localImportUrl(ROOT, 'u/admin/main', '../../../../w/x')).toBeUndefined() + }) + + it('keeps query and fragment characters in the file name', () => { + expect(localImportUrl(ROOT, 'u/admin/main', '/u/a/b?x=1#')).toBe(ROOT + '/u/a/b%3Fx=1%23') + expect(localImportUrl(ROOT, 'u/admin/main', '/u/%2e%2e/%2e%2e')).toBe( + ROOT + '/u/%252e%252e/%252e%252e' + ) + }) +}) + +describe('confinedSubpath', () => { + it('normalizes package file paths', () => { + expect(confinedSubpath('/dist/index.d.ts')).toBe('/dist/index.d.ts') + expect(confinedSubpath('/dist/./a/../b.d.ts')).toBe('/dist/b.d.ts') + expect(confinedSubpath('/../../../file')).toBeUndefined() + expect(confinedSubpath('/a\\..\\b')).toBe('/a%5C..%5Cb') + }) +}) diff --git a/frontend/src/lib/ata/confinedPath.ts b/frontend/src/lib/ata/confinedPath.ts new file mode 100644 index 0000000000..b0c7861d33 --- /dev/null +++ b/frontend/src/lib/ata/confinedPath.ts @@ -0,0 +1,35 @@ +/** + * Normalizes a `/`-rooted file path and encodes each segment, so the result appended to a URL + * prefix always names a file below that prefix: `.`/`..` are resolved here rather than by the + * browser's URL parser, and `?`, `#`, `\` and `%` (so no `%2e%2e`) cannot reach the URL + * unencoded. Returns `undefined` when the path climbs above its root. + */ +export function confinedSubpath(path: string): string | undefined { + const out: string[] = [] + const segments = path.split('/') + // A leading `/` gives an empty first segment, which is the root itself. + if (segments[0] === '') segments.shift() + for (const segment of segments) { + if (segment === '.') continue + if (segment === '..') { + if (out.length === 0) return undefined + out.pop() + continue + } + out.push(encodeURI(segment).replace(/[?#]/g, (c) => encodeURIComponent(c))) + } + return '/' + out.join('/') +} + +/** URL of a script's relative or absolute local import, below the tokened raw-script `root`. */ +export function localImportUrl( + root: string, + scriptPath: string, + specifier: string +): string | undefined { + const path = specifier.startsWith('/') + ? specifier + : '/' + scriptPath + (specifier.startsWith('../') ? '/../' : '/.') + specifier + const confined = confinedSubpath(path) + return confined === undefined ? undefined : root + confined +} diff --git a/frontend/src/lib/ata/index.ts b/frontend/src/lib/ata/index.ts index 004fe7f6df..c920696362 100644 --- a/frontend/src/lib/ata/index.ts +++ b/frontend/src/lib/ata/index.ts @@ -1,4 +1,5 @@ import { isTypescriptRelativePath } from '$lib/relative_imports' +import { localImportUrl } from './confinedPath' import { getDTSFileForModuleWithVersion, getFiletreeForModuleWithVersion, @@ -131,10 +132,8 @@ export const setupTypeAcquisition = (config: ATABootstrapConfig) => { if (depth == 0) { const relativeDeps = depsToGet.filter((f) => isTypescriptRelativePath(f.raw)) relativeDeps.forEach(async (f) => { - let path = f.raw.startsWith('/') - ? f.raw - : '/' + config.scriptPath + (f.raw.startsWith('../') ? '/../' : '/.') + f.raw - let url = config.root + path + let url = localImportUrl(config.root, config.scriptPath ?? '', f.raw) + if (url === undefined) return let localPath = f.raw if ((f.raw.startsWith('.') || f.raw.startsWith('/')) && !f.raw.endsWith('.ts')) { url += '.ts' diff --git a/frontend/src/lib/clientIpTrust.test.ts b/frontend/src/lib/clientIpTrust.test.ts new file mode 100644 index 0000000000..eb85c9ec7d --- /dev/null +++ b/frontend/src/lib/clientIpTrust.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from 'vitest' +import { appendTrustedProxy, clientIpHeaderError, trustedProxiesErrors } from './clientIpTrust' + +// The same inputs as `stored_trusted_proxies_refuse_what_is_not_a_proxy` in `client_ip.rs`: +// the form must refuse exactly what the server refuses. +describe('trustedProxiesErrors', () => { + it('accepts proxies', () => { + for (const ok of ['private, 10.1.2.3, 172.20.0.0/16, caddy, fd00::/8', 'none', '', '::ffff:10.0.0.1']) { + expect(trustedProxiesErrors(ok), ok).toEqual([]) + } + }) + it('refuses what is not a proxy', () => { + for (const bad of [ + '0.0.0.0/0', + '::/0', + '10.0.0.0/8, 104.16.0.0/12', + '162.158.1.1', + '2606:4700::/48', + '10.0.0.0/33', + '10.0.0.256', + 'none, 10.0.0.1', + 'not a host!' + ]) { + expect(trustedProxiesErrors(bad).length, bad).toBeGreaterThan(0) + } + }) + it('refuses X-Forwarded-For as the client IP header', () => { + expect(clientIpHeaderError('X-Forwarded-For')).toBeDefined() + expect(clientIpHeaderError('CF-Connecting-IP')).toBeUndefined() + // YAML mode can put any JSON type here. + expect(clientIpHeaderError(42)).toBeDefined() + expect(trustedProxiesErrors(['10.0.0.1']).length).toBeGreaterThan(0) + }) +}) + +describe('appendTrustedProxy', () => { + it('adds to the default private trust or narrows it, as asked', () => { + expect(appendTrustedProxy(undefined, '1.2.3.4', true)).toBe('private, 1.2.3.4') + expect(appendTrustedProxy('', '10.0.0.5', false)).toBe('10.0.0.5') + expect(appendTrustedProxy('none', '1.2.3.4', true)).toBe('1.2.3.4') + expect(appendTrustedProxy('10.0.0.0/8, caddy', 'caddy', true)).toBe('10.0.0.0/8, caddy') + // Narrowing drops whatever still trusts a whole private range. + expect(appendTrustedProxy('private, 1.2.3.4', '10.0.0.5', false)).toBe('1.2.3.4, 10.0.0.5') + expect(appendTrustedProxy('10.0.0.0/8, caddy', '10.0.0.5', false)).toBe('caddy, 10.0.0.5') + // A subnet inside a private range is a list of proxies, kept. + expect(appendTrustedProxy('192.168.0.0/24, 0.0.0.0/1', '10.0.0.5', false)).toBe( + '192.168.0.0/24, 10.0.0.5' + ) + }) +}) diff --git a/frontend/src/lib/clientIpTrust.ts b/frontend/src/lib/clientIpTrust.ts new file mode 100644 index 0000000000..87c503b130 --- /dev/null +++ b/frontend/src/lib/clientIpTrust.ts @@ -0,0 +1,189 @@ +// Mirrors the checks `windmill_common::client_ip::validate_setting` applies on save, so the +// Client IP settings refuse the same values before the server does. + +/** https://www.cloudflare.com/ips-v4 and /ips-v6, as embedded in `client_ip.rs`. */ +const CLOUDFLARE = [ + '173.245.48.0/20', + '103.21.244.0/22', + '103.22.200.0/22', + '103.31.4.0/22', + '141.101.64.0/18', + '108.162.192.0/18', + '190.93.240.0/20', + '188.114.96.0/20', + '197.234.240.0/22', + '198.41.128.0/17', + '162.158.0.0/15', + '104.16.0.0/13', + '104.24.0.0/14', + '172.64.0.0/13', + '131.0.72.0/22', + '2400:cb00::/32', + '2606:4700::/32', + '2803:f800::/32', + '2405:b500::/32', + '2405:8100::/32', + '2a06:98c0::/29', + '2c0f:f248::/32' +] + +type Net = { v6: boolean; addr: bigint; prefix: number } + +function parseV4(s: string): bigint | undefined { + const parts = s.split('.') + if (parts.length !== 4) return undefined + let n = 0n + for (const p of parts) { + if (!/^\d{1,3}$/.test(p) || Number(p) > 255) return undefined + n = (n << 8n) | BigInt(p) + } + return n +} + +function parseV6(s: string): bigint | undefined { + if (!/^[0-9a-fA-F:.]+$/.test(s) || s.split('::').length > 2) return undefined + const [head, tail] = s.includes('::') ? s.split('::') : [s, undefined] + const groups = (g: string) => (g === '' ? [] : g.split(':')) + const h = groups(head) + const t = tail === undefined ? [] : groups(tail) + const words: number[] = [] + const push = (list: string[], isLast: boolean) => { + for (let i = 0; i < list.length; i++) { + const g = list[i] + if (isLast && i === list.length - 1 && g.includes('.')) { + const v4 = parseV4(g) + if (v4 === undefined) return false + words.push(Number(v4 >> 16n), Number(v4 & 0xffffn)) + } else if (/^[0-9a-fA-F]{1,4}$/.test(g)) { + words.push(parseInt(g, 16)) + } else { + return false + } + } + return true + } + if (!push(h, tail === undefined)) return undefined + const headLen = words.length + if (!push(t, true)) return undefined + if (tail === undefined ? words.length !== 8 : words.length > 7) return undefined + const full = [ + ...words.slice(0, headLen), + ...Array(8 - words.length).fill(0), + ...words.slice(headLen) + ] + return full.reduce((n, w) => (n << 16n) | BigInt(w), 0n) +} + +function parseNet(s: string): Net | undefined { + const [addr, prefix, ...rest] = s.split('/') + if (rest.length) return undefined + const v4 = parseV4(addr) + const v6 = v4 === undefined ? parseV6(addr) : undefined + if (v4 === undefined && v6 === undefined) return undefined + const isV6 = v4 === undefined + const max = isV6 ? 128 : 32 + if (prefix !== undefined && !/^\d{1,3}$/.test(prefix)) return undefined + const p = prefix === undefined ? max : Number(prefix) + if (p > max) return undefined + return { v6: isV6, addr: (v4 ?? v6)!, prefix: p } +} + +function network(n: Net): bigint { + const bits = BigInt(n.v6 ? 128 : 32) + const host = bits - BigInt(n.prefix) + return (n.addr >> host) << host +} + +/** Whether `n` contains `other`'s network address: either containing the other is an overlap. */ +function containsAddr(n: Net, other: Net): boolean { + if (n.v6 !== other.v6) return false + const host = BigInt((n.v6 ? 128 : 32) - n.prefix) + return network(n) >> host === network(other) >> host +} + +const CLOUDFLARE_NETS = CLOUDFLARE.map((c) => [c, parseNet(c)!] as const) + +function isHostname(s: string): boolean { + return ( + s.length <= 253 && + s + .split('.') + .every( + (l) => l.length > 0 && l.length <= 63 && !l.startsWith('-') && /^[A-Za-z0-9_-]+$/.test(l) + ) && + !/^\d+$/.test(s.split('.').pop() ?? '') + ) +} + +/** Why each entry of a `trusted_proxies` value is refused, empty when it can be saved. */ +export function trustedProxiesErrors(value: unknown): string[] { + if (value === undefined || value === null) return [] + if (typeof value !== 'string') return ['must be text: a comma-separated list'] + if (!value || value.trim().toLowerCase() === 'none') return [] + const errors: string[] = [] + for (const s of value + .split(',') + .map((s) => s.trim()) + .filter(Boolean)) { + if (s.toLowerCase() === 'private') continue + const net = parseNet(s) + if (net) { + if (net.prefix === 0) { + errors.push(`${s} trusts every address, so any client could name its own`) + continue + } + const cf = CLOUDFLARE_NETS.find(([, c]) => containsAddr(c, net) || containsAddr(net, c)) + if (cf) { + errors.push(`${s} overlaps Cloudflare's range ${cf[0]}: turn on Trust Cloudflare instead`) + } + } else if (s.toLowerCase() === 'none') { + errors.push('none trusts no proxy only on its own, not among other entries') + } else if (!isHostname(s)) { + errors.push(`${s} is not an IP address, a CIDR, a hostname or private`) + } + } + return errors +} + +/** Why a `client_ip_header` value is refused, if it is. */ +export function clientIpHeaderError(value: unknown): string | undefined { + if (value === undefined || value === null) return undefined + if (typeof value !== 'string') return 'must be text: a header name' + const v = value.trim() + if (!v) return undefined + if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(v)) return `${v} is not a header name` + if (v.toLowerCase() === 'x-forwarded-for') { + return 'X-Forwarded-For is read by default, from the right: leave this empty' + } + return undefined +} + +const PRIVATE_NETS = ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7'].map( + (n) => parseNet(n)! +) + +/** Whether a trusted proxies entry trusts a whole private range, as the server's + * `private_ranges_trusted` counts it. */ +function coversPrivateRange(entry: string): boolean { + if (entry.toLowerCase() === 'private') return true + const net = parseNet(entry) + return net !== undefined && PRIVATE_NETS.some((p) => net.prefix <= p.prefix && containsAddr(net, p)) +} + +/** `list` with `entry` appended, unless it already names it. An empty list stands for the + * default, `private`. `keepDefault` keeps that trust; otherwise the result is narrowed to the + * listed proxies, dropping every entry that trusts a whole private range. */ +export function appendTrustedProxy( + list: string | undefined, + entry: string, + keepDefault: boolean +): string { + const base = list?.trim() ? list : keepDefault ? 'private' : '' + const entries = base + .split(',') + .map((s) => s.trim()) + .filter((s) => s && s.toLowerCase() !== 'none') + .filter((s) => keepDefault || !coversPrivateRange(s)) + if (!entries.includes(entry)) entries.push(entry) + return entries.join(', ') +} diff --git a/frontend/src/lib/components/AppConnectDrawer.svelte b/frontend/src/lib/components/AppConnectDrawer.svelte index 9e5f1a05b1..6cc61e9475 100644 --- a/frontend/src/lib/components/AppConnectDrawer.svelte +++ b/frontend/src/lib/components/AppConnectDrawer.svelte @@ -9,19 +9,19 @@ import GoogleSigninButton from './GoogleSigninButton.svelte' import IconedResourceType from './IconedResourceType.svelte' import { addResourceTitle } from './resourceTypeDisplay' - import type { NativeConnect } from './triggers/native/utils' interface Props { expressOAuthSetup?: boolean workspace?: string - native?: NativeConnect } - let { expressOAuthSetup = false, workspace = undefined, native = undefined }: Props = $props() + let { expressOAuthSetup = false, workspace = undefined }: Props = $props() - /** Set by `open(rt, fillPath)`, not by the parent: which resource this run fills is a - * property of the click, and a prop would go stale between two different rows. */ + /** Set by `open(rt, fillPath, requiredScopes)`, not by the parent: which resource this run + * fills is a property of the click, and a prop would go stale between two different rows. */ let fillPath: string | undefined = $state(undefined) + let requiredScopes: string[] = $state([]) + let viaWorkspaceApp = $state(false) let drawer: Drawer | undefined = $state() let resourceType = $state('') @@ -35,9 +35,18 @@ let appConnectInner: AppConnectInner | undefined = $state(undefined) let rtToLoad: string | undefined = $state('') - /** `fill` connects into a resource that already exists, instead of creating one. */ - export async function open(rt?: string, fill?: string) { + /** `fill` connects into a resource that already exists, instead of creating one; filling an + * OAuth resource reconnects it in place. `scopes` replace the provider's defaults. + * `workspaceApp` connects through the workspace's OAuth app when it has one, as triggers do. */ + export async function open( + rt?: string, + fill?: string, + scopes: string[] = [], + workspaceApp = false + ) { fillPath = fill + requiredScopes = scopes + viaWorkspaceApp = workspaceApp handedOff = false rtToLoad = rt drawer?.openDrawer?.() @@ -80,7 +89,7 @@ size="700px" > <DrawerContent - title={native?.title ?? addResourceTitle(step > 1 ? resourceType : undefined)} + title={addResourceTitle(step > 1 ? resourceType : undefined)} id="add-resource-drawer" on:close={drawer?.closeDrawer} tooltip="Resources represent connections to third party systems. Learn more on how to integrate external APIs." @@ -105,7 +114,8 @@ express={expressOAuthSetup} {workspace} {fillPath} - {native} + {requiredScopes} + {viaWorkspaceApp} /> {#snippet actions()} <div class="flex gap-1"> diff --git a/frontend/src/lib/components/AppConnectInner.svelte b/frontend/src/lib/components/AppConnectInner.svelte index 1e879593e8..183e46766e 100644 --- a/frontend/src/lib/components/AppConnectInner.svelte +++ b/frontend/src/lib/components/AppConnectInner.svelte @@ -17,6 +17,7 @@ ResourceService, WorkspaceService, VariableService, + WorkspaceIntegrationService, type TokenResponse, type ResourceType } from '$lib/gen' @@ -54,7 +55,7 @@ import ResourcePathHint from './ResourcePathHint.svelte' import SchemaForm from './SchemaForm.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' - import type { NativeConnect } from './triggers/native/utils' + import { NATIVE_TRIGGER_SERVICES, serviceForResourceType } from './triggers/native/utils' import { aiResourceTypeAlternative } from './copilot/aiResourceProvider' const operatingWorkspace = useOperatingWorkspace() @@ -76,11 +77,11 @@ * Opt-in: without it this flow still refuses to write over anything. */ fillPath?: string - /** - * Connect a native trigger account: only the path is asked, and `connect` runs the - * popup through the trigger service's OAuth app, whose callback saves the connection. - */ - native?: NativeConnect + /** Scopes the caller needs, requested instead of the provider's defaults. */ + requiredScopes?: string[] + /** Connect through the workspace's OAuth app when it has one: a trigger's connection, or a + * reconnect of one made through it. Other connections use the instance's clients. */ + viaWorkspaceApp?: boolean /** What the caller's primary button does on the current step. */ actionLabel?: string /** Whether the caller should offer Back on the current step. */ @@ -96,7 +97,8 @@ express = false, workspace = undefined, fillPath = undefined, - native = undefined, + requiredScopes = [], + viaWorkspaceApp = false, actionLabel = $bindable(), canGoBack = $bindable() }: Props = $props() @@ -131,7 +133,14 @@ let filter = $state('') let value: string = $state('') let valueToken: TokenResponse | undefined = undefined - let connects: string[] | undefined = $state(undefined) + let instanceConnects: string[] | undefined = $state(undefined) + /** Resource types with a workspace OAuth app, which only trigger connections go through. */ + let workspaceApps: string[] = $state([]) + let connects = $derived( + instanceConnects && viaWorkspaceApp + ? [...new Set([...instanceConnects, ...workspaceApps])] + : instanceConnects + ) /** Per-provider instance-entry metadata, keyed by provider name. */ let connectsInfo: Record< string, @@ -154,6 +163,12 @@ // (e.g. `docusign_sandbox`) used to look up credentials/URLs at runtime // and stored on `account.client` so token refresh hits the right endpoint. let connectClient: string = $state('') + /** The workspace app's service when the current connection goes through it. */ + let workspaceAppService = $derived( + viaWorkspaceApp && workspaceApps.includes(connectClient) + ? serviceForResourceType(connectClient) + : undefined + ) let connectsManual: { key: string; img?: string; instructions: string[] }[] | undefined = $state(undefined) let resourceTypeDescriptions: Record<string, string> = $state({}) @@ -318,7 +333,7 @@ ? defaultCcScopes() : useUserToken ? [...(registryEntry()?.user_scope_options ?? []), ...(registryEntry()?.user_scopes ?? [])] - : [...(registryEntry()?.scope_options ?? []), ...instanceScopes] + : [...(registryEntry()?.scope_options ?? []), ...instanceScopes, ...requiredScopes] ) /** Their slice of the resource type's schema, so they render with the type's own @@ -353,6 +368,7 @@ * sign-in the registry declares but the instance holds no client for is listed disabled, * so the user learns it exists and who can turn it on. */ let methodOptions = $derived.by(() => { + if (workspaceAppService) return [{ method: 'auth_code' as ConnectMethod, disabled: false }] const signIn = isSharedConnect(connectClient) && !authCodeUnavailable const opts: { method: ConnectMethod; disabled: boolean }[] = [] if (signIn || (registryEntry()?.grant_types?.includes('authorization_code') ?? false)) { @@ -430,7 +446,11 @@ ? defaultCcScopes() : useUserToken ? (registryEntry()?.user_scopes ?? []) - : instanceScopes + : // A trigger's connection, or a reconnect, asks for what its caller needs rather + // than the provider's defaults, meant for scripts (Google's are admin directory ones). + requiredScopes.length > 0 + ? [...new Set(requiredScopes)] + : instanceScopes } function backTarget(s: number): number { @@ -438,7 +458,7 @@ } function canBackFrom(s: number): boolean { const t = backTarget(s) - return !native && !express && t > 0 && (t > 1 || !openedOnType) + return !express && t > 0 && (t > 1 || !openedOnType) } /** Clear CC inputs and scopes so a previous selection never leaks into a new one */ @@ -488,13 +508,6 @@ let pathError = $state('') export async function open(rt?: string) { - if (native) { - resourceType = rt ?? '' - manual = false - path = '' - step = 5 - return - } openedOnType = !!rt if (!rt) { loadResourceTypes() @@ -566,16 +579,24 @@ } async function loadConnects() { - if (!connects) { + if (!instanceConnects) { + const apps = WorkspaceIntegrationService.listNativeTriggerWorkspaceApps({ + workspace: effectiveWorkspace + }) + .then((services) => services.map((s) => NATIVE_TRIGGER_SERVICES[s].resourceType)) + // Absent from builds without integration triggers. + .catch(() => [] as string[]) try { const list = (await OauthService.listOauthConnects()).filter( (x) => x.name != 'supabase_wizard' ) - connects = list.map((x) => x.name) connectsInfo = Object.fromEntries(list.map((x) => [x.name, x])) + workspaceApps = await apps + instanceConnects = list.map((x) => x.name) } catch (e) { - connects = [] connectsInfo = {} + workspaceApps = await apps + instanceConnects = [] console.error('Error loading OAuth connects', e) } } @@ -588,7 +609,7 @@ // provider, not a registry entry. run(() => { isGoogleSignin = - (step == 3 || (!!native && step == 5)) && + step == 3 && !manual && !useClientCredentials && (resourceType == 'google' || @@ -615,14 +636,14 @@ clientSecret.trim() == '' || (!!ccInstanceMeta && ccInstance.trim() == '')))) || step == 4 || - (step == 5 && (pathError != '' || (!!native && !path))) || + (step == 5 && pathError != '') || // The manual form's own validity: it must not hold Next once the form is left. (step == 3 && manual && !isValid) }) run(() => { canGoBack = canBackFrom(step) - actionLabel = native || (step == 3 && !manual) ? 'Connect' : step <= 2 ? 'Next' : 'Save' + actionLabel = step == 3 && !manual ? 'Connect' : step <= 2 ? 'Next' : 'Save' }) export async function loadResourceTypes() { @@ -756,6 +777,12 @@ /** Reads what the provider offers; `selectMethod` then sets the grant and its scopes. */ async function getScopesAndParams() { + if (workspaceAppService) { + instanceScopes = registryEntry()?.scopes ?? [] + extra_params = [] + supportsClientCredentials = false + return + } if (!connects?.includes(connectClient)) { // No instance OAuth client: defaults come from the static registry instead. instanceScopes = registryEntry()?.scopes ?? [] @@ -804,16 +831,6 @@ } } export async function next() { - if (native) { - step = 4 - try { - await native.connect(path) - dispatch('close') - } catch { - step = 5 - } - return - } if (step == 1) { linkedSecrets = [] // The OAuth path fills `resourceFields` into the same map, and fields typed into @@ -902,19 +919,31 @@ * Requires user interaction and consent * Opens popup for user to authenticate with OAuth provider */ - const url = new URL(`/api/oauth/connect/${connectClient}`, window.location.origin) - // An empty `scopes` still overrides the instance's bot scopes. - url.searchParams.append('scopes', useUserToken ? '' : scopes.join('+')) - if (useUserToken) { - url.searchParams.append('user_scope', scopes.join(',')) - } - if (extra_params.length > 0) { - extra_params.forEach(([key, value]) => url.searchParams.append(key, value)) + let url: string + if (workspaceAppService) { + try { + url = await WorkspaceIntegrationService.generateNativeTriggerServiceConnectUrl({ + workspace: effectiveWorkspace, + serviceName: workspaceAppService, + requestBody: { scopes } + }) + } catch (e: any) { + sendUserToast(`Could not start the connection: ${e.body ?? e.message}`, true) + return + } + } else { + const instanceUrl = new URL(`/api/oauth/connect/${connectClient}`, window.location.origin) + // An empty `scopes` still overrides the instance's bot scopes. + instanceUrl.searchParams.append('scopes', useUserToken ? '' : scopes.join('+')) + if (useUserToken) { + instanceUrl.searchParams.append('user_scope', scopes.join(',')) + } + extra_params.forEach(([key, value]) => instanceUrl.searchParams.append(key, value)) + url = instanceUrl.toString() } window.addEventListener('message', popupListener) window.addEventListener('storage', handleStorageEvent) - console.log('opening popup', url.toString()) - window.open(url.toString(), '_blank', 'popup=true') + window.open(url, '_blank', 'popup=true') step += 1 } } else { @@ -923,12 +952,17 @@ throw Error('Path is not set') } // Check if variable paths already exist + // Reconnecting an OAuth resource fills it at its own path, and its token variable takes + // the new token and account in place, keeping its sharing. + let reconnecting = false if (!manual || linkedSecrets.length <= 1) { const exists = await VariableService.existsVariable({ workspace: effectiveWorkspace, path }) - if (exists) { + if (exists && !manual && !!valueToken && !!fillPath && path === fillPath) { + reconnecting = true + } else if (exists) { throw Error(`Variable at path ${path} already exists. Delete it or pick another path`) } } else { @@ -959,6 +993,7 @@ // its value replaced with credentials for a different provider, while keeping its // own type — destroying a working resource that has nothing to do with the import. const filling = exists && !!fillPath && path === fillPath + let occupantValue: Record<string, any> | undefined if (filling) { // Fails closed. Only a read that succeeds and answers with exactly this type // permits the write — a failed read, a missing type, or any other type all @@ -967,9 +1002,12 @@ // and could not run. let occupantType: string | undefined try { - occupantType = ( - await ResourceService.getResource({ workspace: effectiveWorkspace, path }) - )?.resource_type + const occupant = await ResourceService.getResource({ + workspace: effectiveWorkspace, + path + }) + occupantType = occupant?.resource_type + occupantValue = occupant?.value as Record<string, any> | undefined } catch (e: any) { throw Error( `Could not read what is already at ${path} (${e?.body ?? e?.message ?? e}), ` + @@ -1021,11 +1059,15 @@ } let accountData: any = undefined - if (valueToken?.expires_in != undefined) { + // A workspace app's token keeps an account even when it never expires (GitHub): the + // account records the app, which a reconnect must go through again. It never refreshes. + if (valueToken?.expires_in != undefined || (valueToken && workspaceAppService)) { accountData = { refresh_token: valueToken.refresh_token ?? '', - expires_in: valueToken.expires_in, - client: connectClient, + expires_in: valueToken.expires_in ?? 100 * 365 * 24 * 3600, + // A workspace app's token refreshes through the app, found by its service. + client: workspaceAppService ?? connectClient, + is_workspace_integration: !!workspaceAppService, grant_type: valueToken.grant_type || 'authorization_code' } @@ -1078,10 +1120,17 @@ ws_specific: wsSpecific } if (accountData) { - // Creates the variable with the account it refreshes through, in one transaction. + // Creates the variable with the account it refreshes through, in one transaction, + // or on reconnect swaps both into the existing variable. await OauthService.createAccount({ workspace: effectiveWorkspace, - requestBody: { ...accountData, variable: tokenVariable } + requestBody: { ...accountData, variable: tokenVariable, replace: reconnecting } + }) + } else if (reconnecting) { + await VariableService.updateVariable({ + workspace: effectiveWorkspace, + path, + requestBody: { value, unlink_account: true } }) } else { await VariableService.createVariable({ @@ -1141,7 +1190,11 @@ await ResourceService.updateResource({ workspace: effectiveWorkspace, path, - requestBody: { value: resourceValue, description } + // A reconnected resource keeps its fields and description; the import's stub has + // neither. + requestBody: reconnecting + ? { value: { ...occupantValue, ...resourceValue } } + : { value: resourceValue, description } }) } else { await ResourceService.createResource({ @@ -1290,7 +1343,7 @@ <!-- Only once a provider with a real choice of method is picked: with manual entry as the only way in, the form is the whole flow and a stepper would only add noise. --> {#snippet wizardSteps()} - {#if !native && methodStepShown} + {#if methodStepShown} <div class="shrink-0 mb-6 flex justify-center"> <Stepper tabs={manual @@ -1398,7 +1451,7 @@ onSynced={async () => { connectsManual = undefined await loadResourceTypes() - connects = undefined + instanceConnects = undefined await loadConnects() }} /> @@ -1638,56 +1691,47 @@ <Label label="Path"> <Path initialPath="" - namePlaceholder={native?.defaultName ?? defaultName} - fullNamePlaceholder={native?.defaultName} + namePlaceholder={defaultName} bind:error={pathError} bind:path kind="resource" /> </Label> - {#if native} - <p class="text-xs text-secondary"> - The account is saved as a resource and its token as a variable at this path. Anyone who can - read them can create triggers that act as this account. - </p> - {:else} - <LabelsInput bind:labels class="-mt-5" /> - {#if deployTo} - <Label - label="Workspace specific" - tooltip="Prevents this resource from being deployed to prod/staging" - > - <Toggle bind:checked={wsSpecific} /> - </Label> - {/if} - <!-- Not for express or `fillPath`, which save as soon as the token arrives: the fields - are then filled by editing the resource. --> - {#if step == 5 && !manual && !express && !fillPath && resourceFields.length > 0} - <Label - label="Connection details" - tooltip="Saved on the resource with the token, and editable later" - class="mt-6" - > - <SchemaForm onlyMaskPassword noDelete schema={resourceFieldsSchema} bind:args /> - </Label> - {/if} - {#if apiTokenApps[resourceType] || !manual} - <ul class="mt-6"> - <li class="text-xs text-primary font-normal"> - 1. A secret variable containing the {apiTokenApps[resourceType]?.linkedSecret ?? - 'token'} - <span class="font-semibold text-emphasis">{truncateRev(value, 5, '*****')}</span> - will be stored a - <span class="font-mono whitespace-nowrap text-emphasis">{path}</span>. - </li> - <li class="mt-2 text-xs text-primary font-normal"> - 2. The resource containing that token will be stored at the same path <span - class="font-mono whitespace-nowrap text-emphasis">{path}</span - >. The Variable and Resource will be "linked together", they will be deleted and renamed - together. - </li></ul - > - {/if} + <LabelsInput bind:labels class="-mt-5" /> + {#if deployTo} + <Label + label="Workspace specific" + tooltip="Prevents this resource from being deployed to prod/staging" + > + <Toggle bind:checked={wsSpecific} /> + </Label> + {/if} + <!-- Not for express or `fillPath`, which save as soon as the token arrives: the fields + are then filled by editing the resource. --> + {#if step == 5 && !manual && !express && !fillPath && resourceFields.length > 0} + <Label + label="Connection details" + tooltip="Saved on the resource with the token, and editable later" + class="mt-6" + > + <SchemaForm onlyMaskPassword noDelete schema={resourceFieldsSchema} bind:args /> + </Label> + {/if} + {#if apiTokenApps[resourceType] || !manual} + <ul class="mt-6"> + <li class="text-xs text-primary font-normal"> + 1. A secret variable containing the {apiTokenApps[resourceType]?.linkedSecret ?? 'token'} + <span class="font-semibold text-emphasis">{truncateRev(value, 5, '*****')}</span> + will be stored a + <span class="font-mono whitespace-nowrap text-emphasis">{path}</span>. + </li> + <li class="mt-2 text-xs text-primary font-normal"> + 2. The resource containing that token will be stored at the same path <span + class="font-mono whitespace-nowrap text-emphasis">{path}</span + >. The Variable and Resource will be "linked together", they will be deleted and renamed + together. + </li></ul + > {/if} {/if} {/if} diff --git a/frontend/src/lib/components/AuthSettings.svelte b/frontend/src/lib/components/AuthSettings.svelte index 8265e5d51f..e58879ce38 100644 --- a/frontend/src/lib/components/AuthSettings.svelte +++ b/frontend/src/lib/components/AuthSettings.svelte @@ -761,29 +761,6 @@ {/if} </div> </div> - {#if k === 'gworkspace'} - <div> - <Toggle - options={{ - right: - 'Allow workspace admins to set up Google integration triggers using these credentials' - }} - checked={oauths[k]?.share_with_workspaces ?? false} - on:change={(e) => { - if (oauths && oauths[k]) { - oauths[k] = { ...oauths[k], share_with_workspaces: e.detail } - } - }} - /> - {#if oauths[k]?.share_with_workspaces} - <p class="text-xs text-tertiary mt-1"> - Workspace admins will be able to connect Google integration triggers without - configuring their own OAuth client. The credentials are not exposed to them. - Connections use the redirect URI above. - </p> - {/if} - </div> - {/if} </div> </div> {/if} diff --git a/frontend/src/lib/components/CenteredModal.svelte b/frontend/src/lib/components/CenteredModal.svelte index 9c732eb366..4f198276ad 100644 --- a/frontend/src/lib/components/CenteredModal.svelte +++ b/frontend/src/lib/components/CenteredModal.svelte @@ -49,13 +49,15 @@ : 'h-screen'} p-4 relative bg-surface-secondary {containOverflow ? 'overflow-hidden' : 'overflow-auto'}" - class:items-center={centerVertically} style="scrollbar-gutter: stable both-edges;" bind:clientHeight={height} > + <!-- Centred with auto margins, not `items-center` on the scroller: a card taller than the + window would overflow both ways, and its top would be out of scroll reach. --> <div class={twMerge( 'flex flex-col gap-2 items-center w-full pb-8', + centerVertically && 'my-auto', containOverflow ? 'min-h-0' : 'h-fit', containOverflow ? '' : height > 1080 ? 'pt-28' : 'pt-12' )} diff --git a/frontend/src/lib/components/CompareWorkspaces.svelte b/frontend/src/lib/components/CompareWorkspaces.svelte index e265c453dc..63eb92c6cd 100644 --- a/frontend/src/lib/components/CompareWorkspaces.svelte +++ b/frontend/src/lib/components/CompareWorkspaces.svelte @@ -56,7 +56,7 @@ type DeployResult } from '$lib/utils_workspace_deploy' import { asSyncDeploy } from '$lib/deployOrigin' - import { isTriggerOrScheduleKind } from 'windmill-utils-internal' + import { isTriggerOrScheduleKind } from 'windmill-utils-internal/deploy' import Tooltip from './Tooltip.svelte' import OnBehalfOfSelector, { needsOnBehalfOfSelection, diff --git a/frontend/src/lib/components/DBTable.svelte b/frontend/src/lib/components/DBTable.svelte index 0ea2ec0fc5..8c6bba513c 100644 --- a/frontend/src/lib/components/DBTable.svelte +++ b/frontend/src/lib/components/DBTable.svelte @@ -15,8 +15,16 @@ const MIN_COL_WIDTH = 60 const DEFAULT_COL_WIDTH = 150 const MAX_AUTO_COL_WIDTH = 400 - // Header padding plus its sort and key icons. - const HEADER_CHROME = 48 + // Header padding, the sort arrow with its gap (kept free so sorting never truncates the + // label), and the border. + const HEADER_CHROME = 34 + // A key, link or join icon with its gap. + const HEADER_ICON_WIDTH = 16 + // A pinned header's pin icon with its gap, and the thicker border at the pinned block's edge. + const PIN_CHROME = 17 + // The filter button in a filterable column's header, with its margin. + const HEADER_FILTER_WIDTH = 24 + const HEADER_FILTER_DEBOUNCE = 300 const CELL_PADDING = 18 // A double click starts with a click: following a foreign key waits this long // so the double click can edit the cell instead. @@ -43,6 +51,7 @@ Columns3, EyeOff, Download, + Filter, KeyRound, Link, Merge, @@ -105,6 +114,8 @@ joinTargets?: DbJoinTarget[] /** Offered from the add-column button: adding a column to the table itself. */ onNewColumn?: () => void + /** Hides the button that downloads the loaded rows, for a file whose owner disabled downloads. */ + disableDownload?: boolean } let { dbTableOps, @@ -114,7 +125,8 @@ onRowFilterApplied, layoutStorageKey, joinTargets, - onNewColumn + onNewColumn, + disableDownload = false }: Props = $props() const storedLayout = untrack(() => @@ -162,6 +174,65 @@ ) let columnFilters = $derived(columnFiltersOf(filters, filterSchema)) let hasFilters = $derived(!!quicksearch || !!filterWhere) + /** The column whose header filter is open, and the value typed there. A header filter + * writes the same entry the search bar does, so each shows the other's filter. */ + let headerFilter: { column: string; key: string; draft: string } | undefined = $state(undefined) + /** The typed value not yet written to `filters`. Written when typing pauses, and at once + * when the popover closes or another column is typed in, so no keystroke is lost. */ + let pendingHeaderFilter: { key: string; draft: string } | undefined + let headerFilterTimer: ReturnType<typeof setTimeout> | undefined + function setHeaderFilter(key: string, boolean: boolean, draft: string) { + const { [key]: current, ...rest } = filters + const trimmed = draft.trim() + const value = trimmed ? (boolean ? trimmed === 'true' : trimmed) : undefined + if (value === current) return + filters = value === undefined ? rest : { ...rest, [key]: value } + } + function flushHeaderFilter() { + clearTimeout(headerFilterTimer) + const pending = pendingHeaderFilter + pendingHeaderFilter = undefined + if (pending) setHeaderFilter(pending.key, false, pending.draft) + } + /** Filters as the reader types; a half-typed comparison such as `>` matches no row. */ + function typeHeaderFilter(key: string, draft: string) { + if (pendingHeaderFilter && pendingHeaderFilter.key !== key) flushHeaderFilter() + if (headerFilter?.key === key) headerFilter.draft = draft + pendingHeaderFilter = { key, draft } + clearTimeout(headerFilterTimer) + headerFilterTimer = setTimeout(flushHeaderFilter, HEADER_FILTER_DEBOUNCE) + } + /** For a popover's content: Escape closes that popover only. Left to the window, it + * would also close a drawer the table sits in. */ + function escapeClosesOnly(close: () => void) { + return (e: KeyboardEvent) => { + if (e.key !== 'Escape') return + e.stopPropagation() + close() + } + } + /** Where focus goes when a header filter closes: back to its button, unless the click + * that closed it put focus somewhere else (the search bar). */ + function headerFilterCloseFocus(column: string): HTMLElement | null { + const active = document.activeElement + if (active && active !== document.body) return null + return ( + scrollEl?.querySelector<HTMLElement>( + `[data-header-column="${CSS.escape(column)}"] [data-popover]` + ) ?? null + ) + } + function closeHeaderFilter() { + flushHeaderFilter() + headerFilter = undefined + } + /** The open popover's text: what was typed, unless the filter was changed from elsewhere + * (the search bar, a chip removed) since. */ + function headerFilterDraft(key: string): string { + const applied = filters[key] === undefined ? '' : String(filters[key]) + const draft = headerFilter?.key === key ? headerFilter.draft : applied + return pendingHeaderFilter?.key === key || draft.trim() === applied ? draft : applied + } $effect(() => { const f = rowFilter @@ -233,6 +304,9 @@ colDefs: dbTableOps.colDefs, quicksearch, filterWhere, + // Sources that filter rows themselves read the values: `>` and `abc` on a number + // column render the same SQL but are different requests. + columnFilters, sort, joins, workspace: $operatingWorkspace, @@ -243,18 +317,22 @@ // A refresh keeps the scroll position; a new query starts from the top. const onlyRefreshed = prevQuery && deepEqual({ ...query, refreshCount: 0 }, { ...prevQuery, refreshCount: 0 }) + const onlySorted = + prevQuery && deepEqual({ ...query, sort: undefined }, { ...prevQuery, sort: undefined }) prevQuery = query if (!onlyRefreshed && scrollEl) scrollEl.scrollTop = 0 - reload() + reload(onlySorted) }) }) - function reload() { + /** `keepCount`: the rows are the same, only their order changed. */ + function reload(keepCount = false) { generation += 1 blocks = {} endRow = undefined - rowCount = undefined editing = undefined + if (keepCount && rowCount !== undefined) return + rowCount = undefined if (!$operatingWorkspace) return const gen = generation dbTableOps @@ -370,7 +448,10 @@ const sizedWidths = Object.fromEntries( [...sizedColumns].filter((f) => widths[f] !== undefined).map((f) => [f, widths[f]]) ) - if (Object.keys(sizedWidths).length) layout.widths = sizedWidths + if (Object.keys(sizedWidths).length) { + layout.widths = sizedWidths + layout.widthsFitFilterButton = true + } if (Object.keys(pinned).length) layout.pinned = $state.snapshot(pinned) if (joins.length) layout.joins = $state.snapshot(joins) if (hidden.length) layout.hidden = $state.snapshot(hidden) @@ -381,6 +462,8 @@ // ── Column widths ──────────────────────────────────────────────────────── let widths: Record<string, number> = $state({ ...storedLayout.widths }) let sizedColumns = new Set<string>(Object.keys(storedLayout.widths ?? {})) + // Widths saved before headers had a filter button can be too narrow for their label. + let widenStoredWidths = !storedLayout.widthsFitFilterButton let autoSizedFor: ColumnDef[] | undefined let measureCtx: CanvasRenderingContext2D | null | undefined @@ -396,16 +479,32 @@ const family = getComputedStyle(scrollEl).fontFamily const rows = loadedRows().slice(0, 300) const next = { ...widths } + const headerWidth = (col: ColumnDef) => + textWidth(col.field, `600 12px ${family}`) + + HEADER_CHROME + + (col.isprimarykey || fkByColumn[col.field] || joinedAliases.has(col.field) + ? HEADER_ICON_WIDTH + : 0) + + (pinned[col.field] ? PIN_CHROME : 0) + + (filterSchema.keyOfColumn[col.field] ? HEADER_FILTER_WIDTH : 0) for (const col of columns) { - if (only ? !only.includes(col.field) : sizedColumns.has(col.field)) continue - let w = textWidth(col.field, `600 12px ${family}`) + HEADER_CHROME + if (only ? !only.includes(col.field) : sizedColumns.has(col.field)) { + if (!only && widenStoredWidths && next[col.field] !== undefined) + next[col.field] = Math.ceil( + Math.max(next[col.field], Math.min(MAX_AUTO_COL_WIDTH, headerWidth(col))) + ) + continue + } + let w = headerWidth(col) for (const row of rows) { const text = formatCell(row[col.field]).slice(0, 200) || 'NULL' w = Math.max(w, textWidth(text, `400 12px ${family}`) + CELL_PADDING) } - next[col.field] = Math.round(Math.min(MAX_AUTO_COL_WIDTH, Math.max(MIN_COL_WIDTH, w))) + // Rounded up: a label a fraction of a pixel wider than its cell is cut. + next[col.field] = Math.ceil(Math.min(MAX_AUTO_COL_WIDTH, Math.max(MIN_COL_WIDTH, w))) sizedColumns.add(col.field) } + if (!only) widenStoredWidths = false widths = next saveLayout() } @@ -922,6 +1021,96 @@ {/if} {/snippet} +{#snippet headerFilterButton(col: ColumnDef, key: string)} + {@const boolean = dbColumnKind(col.datatype) === 'boolean'} + {@const number = dbColumnKind(col.datatype) === 'number'} + {@const active = filters[key] !== undefined && filters[key] !== ''} + {@const open = headerFilter?.column === col.field} + <Popover + floatingConfig={{ strategy: 'fixed', placement: 'bottom-start' }} + closeFocus={() => headerFilterCloseFocus(col.field)} + bind:isOpen={ + () => open, + (isOpen) => { + if (isOpen) { + flushHeaderFilter() + headerFilter = { column: col.field, key, draft: active ? String(filters[key]) : '' } + } else if (open) closeHeaderFilter() + } + } + class={twMerge( + 'mr-1 flex h-5 w-5 shrink-0 items-center justify-center rounded hover:bg-surface-hover', + active || open + ? 'text-accent' + : 'text-secondary opacity-0 group-hover/header:opacity-100 focus-visible:opacity-100' + )} + triggerAttrs={{ + 'aria-label': `Filter ${col.field}`, + title: active ? `Filtered: ${filters[key]}` : `Filter ${col.field}` + }} + > + {#snippet trigger()} + <Filter size={12} /> + {/snippet} + {#snippet content()} + <!-- svelte-ignore a11y_no_static_element_interactions --> + <div class="flex w-64 flex-col gap-2 p-3" onkeydown={escapeClosesOnly(closeHeaderFilter)}> + <span class="truncate text-xs font-semibold text-emphasis">Filter {col.field}</span> + {#if boolean} + <Select + items={[ + { label: 'true', value: 'true' }, + { label: 'false', value: 'false' } + ]} + bind:value={ + () => headerFilterDraft(key) || undefined, + (v) => { + if (headerFilter) headerFilter.draft = v ?? '' + setHeaderFilter(key, true, v ?? '') + } + } + placeholder="Value" + size="sm" + /> + {:else} + <TextInput + bind:value={() => headerFilterDraft(key), (v) => typeHeaderFilter(key, String(v ?? ''))} + size="sm" + inputProps={{ + placeholder: number ? '10, >10, <=5' : 'Contains', + 'aria-label': `Filter ${col.field}`, + onkeydown: (e: KeyboardEvent) => { + if (e.key === 'Enter') closeHeaderFilter() + } + }} + /> + <span class="text-2xs text-secondary"> + {number + ? 'A number, or a comparison: =, >, >=, <, <=, !=' + : 'Rows whose value contains this text. Start with = for an exact match.'} + </span> + {/if} + {#if active} + <div class="flex justify-end"> + <Button + variant="subtle" + unifiedSize="sm" + onClick={() => { + pendingHeaderFilter = undefined + clearTimeout(headerFilterTimer) + setHeaderFilter(key, boolean, '') + headerFilter = undefined + }} + > + Clear + </Button> + </div> + {/if} + </div> + {/snippet} + </Popover> +{/snippet} + {#snippet addColumnHeader()} {#if canAddColumn} <div @@ -1035,18 +1224,23 @@ /> <div class="h-full relative flex flex-col"> - <div class="flex justify-between items-center bg-surface-input pr-2"> - <FilterSearchbar - class="grow rounded-none !border-0" - size="lg" - searchIconPosition="left" - dropdownMaxWidth={480} - dropdownOffsetY={1} - schema={filterSchema.schema} - bind:value={filters} - placeholder="Search, or filter by column..." - /> - <div class="flex shrink-0 items-center gap-2 text-xs text-secondary"> + <div class="flex flex-wrap justify-between items-center bg-surface-input pr-2"> + <!-- The search bar stops its mousedown, which an open header filter would take as an + outside click; close that popover first so the bar gets the focus. --> + <div class="contents" onmousedowncapture={() => headerFilter && closeHeaderFilter()}> + <FilterSearchbar + class="grow min-w-48 rounded-none !border-0" + size="lg" + searchIconPosition="left" + dropdownMaxWidth={480} + dropdownOffsetY={1} + schema={filterSchema.schema} + bind:value={filters} + placeholder="Search, or filter by column..." + /> + </div> + <!-- Wraps under the search bar in a narrow panel rather than being cut off. --> + <div class="ml-auto flex shrink-0 items-center gap-2 pl-2 text-xs text-secondary"> {#if totalRows > 0 && endRow !== 0} <span class="whitespace-nowrap"> {Math.min(firstVisible + 1, totalRows)}–{Math.min(lastVisible, totalRows)} @@ -1055,14 +1249,16 @@ {/if} </span> {/if} - <Button - startIcon={{ icon: Download }} - variant="subtle" - unifiedSize="sm" - iconOnly - title="Download loaded rows as CSV" - onClick={downloadCsv} - /> + {#if !disableDownload} + <Button + startIcon={{ icon: Download }} + variant="subtle" + unifiedSize="sm" + iconOnly + title="Download loaded rows as CSV" + onClick={downloadCsv} + /> + {/if} <div class="flex" bind:this={columnsAnchor}> <Popover floatingConfig={{ strategy: 'fixed', placement: 'bottom-end' }} @@ -1082,7 +1278,12 @@ </Button> {/snippet} {#snippet content()} - <div class="flex w-60 flex-col py-1" data-testid="db-columns-picker"> + <!-- svelte-ignore a11y_no_static_element_interactions --> + <div + class="flex w-60 flex-col py-1" + data-testid="db-columns-picker" + onkeydown={escapeClosesOnly(() => (columnsPickerOpen = false))} + > <label class="flex cursor-pointer items-center gap-2 border-b px-3 py-1.5 text-xs font-medium text-emphasis hover:bg-surface-hover" > @@ -1214,7 +1415,7 @@ {/if} <div class={twMerge( - 'relative shrink-0 flex items-center border-r', + 'group/header relative shrink-0 flex items-center border-r', // Above the other header cells, whose resize handles sit at z-10. pin ? 'sticky z-20 bg-surface-tertiary dark:bg-surface-input' : '', // The pinned block's edge against the scrolling columns is a pixel thicker. @@ -1251,6 +1452,9 @@ <Icon size={12} class="shrink-0 text-secondary" /> {/if} </button> + {#if filterSchema.keyOfColumn[col.field]} + {@render headerFilterButton(col, filterSchema.keyOfColumn[col.field])} + {/if} <!-- svelte-ignore a11y_no_static_element_interactions --> <div class="absolute -right-1 top-0 bottom-0 w-2 z-10 cursor-col-resize hover:bg-border-selected/50" diff --git a/frontend/src/lib/components/Dev.svelte b/frontend/src/lib/components/Dev.svelte index d6185c00e2..6515807dde 100644 --- a/frontend/src/lib/components/Dev.svelte +++ b/frontend/src/lib/components/Dev.svelte @@ -30,6 +30,7 @@ import { onDestroy, onMount, setContext, untrack } from 'svelte' import DarkModeToggle from '$lib/components/sidebar/DarkModeToggle.svelte' import { page } from '$app/state' + import { isFromWindowEmbedder } from '$lib/utils/embedderMessage' import { getUserExt } from '$lib/user' import FlowPreviewButtons from './flows/header/FlowPreviewButtons.svelte' import FlowModuleSchemaMap from './flows/map/FlowModuleSchemaMap.svelte' @@ -271,8 +272,8 @@ modeInitialized = true } - const el = (event) => { - // sendUserToast(`Received message from parent ${event.data.type}`, true) + const el = (event: MessageEvent) => { + if (!isFromWindowEmbedder(event)) return if (event.data.type == 'runTest') { runTest() event.preventDefault() diff --git a/frontend/src/lib/components/DisplayResult.svelte b/frontend/src/lib/components/DisplayResult.svelte index 2523f6b862..42026c81f8 100644 --- a/frontend/src/lib/components/DisplayResult.svelte +++ b/frontend/src/lib/components/DisplayResult.svelte @@ -5,8 +5,16 @@ import { json } from 'svelte-highlight/languages' import DbtRunResult from '$lib/components/dbt/DbtRunResult.svelte' import { parseDbtRun } from '$lib/components/dbt/parseDbtRun' - import { copyToClipboard, parseS3Object, roughSizeOfObject } from '$lib/utils' + import { + copyToClipboard, + isS3ImageKey, + parseS3Object, + roughSizeOfObject, + s3ImagePreviewUrl + } from '$lib/utils' import ExpandableImage from '$lib/components/common/image/ExpandableImage.svelte' + import { getImageOpener } from '$lib/components/common/image/imageOpener' + import type { ImageResultFormat, ResultPath } from '$lib/components/sessions/previewRouter' import { downloadBlob, downloadViaClient, @@ -22,11 +30,17 @@ PanelRightOpen, Table2, Braces, + Brackets, Highlighter, ArrowDownFromLine, Database, + Eye, + FileImage, + FileText, Loader2 } from 'lucide-svelte' + import Tooltip from './Tooltip.svelte' + import MeltTooltip from './meltComponents/Tooltip.svelte' import DataTestsResult from './DataTestsResult.svelte' import Portal from '$lib/components/Portal.svelte' import DisplayResultControlBar from './DisplayResultControlBar.svelte' @@ -36,19 +50,24 @@ import Alert from './common/alert/Alert.svelte' import AutoDataTable from './table/AutoDataTable.svelte' import Markdown from 'svelte-exmarkdown' + import { markdownPlugins } from './markdownPlugins' + import { + approvalPageHref, + resumeRequestCredentials, + signedResumeUrl + } from '$lib/utils/approvalResultUrls' import { markdownProse } from './markdownProse' import Toggle from './Toggle.svelte' import FileDownload from './common/fileDownload/FileDownload.svelte' - import ParqetTableRenderer from './ParqetCsvTableRenderer.svelte' + import S3ObjectTable from './common/fileDownload/S3ObjectTable.svelte' + import { serverTableFormat } from './s3TableOps' import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte' import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte' import MapResult from './MapResult.svelte' import ChartResult from './display/ChartResult.svelte' import { isChartResult } from './display/displayCatalog' - import DownloadCsv from './table/DownloadCsv.svelte' import { convertJsonToCsv } from './table/tableUtils' - import Tooltip from './Tooltip.svelte' import HighlightTheme from './HighlightTheme.svelte' import type { DisplayResultUi } from './custom_ui' import { getContext, hasContext, createEventDispatcher, onDestroy, untrack } from 'svelte' @@ -132,6 +151,9 @@ * run from the next, or a second one continues the first one's fold. */ runKey?: string | undefined + /** Where `result` sits inside the job's result, for a nested render; null when it + * cannot be addressed from the job (an agent's structured output). */ + resultPath?: ResultPath | null workspaceId?: string | undefined hideAsJson?: boolean noControls?: boolean @@ -158,6 +180,7 @@ disableExpand = false, jobId = undefined, runKey = undefined, + resultPath = [], workspaceId = undefined, hideAsJson = false, noControls = false, @@ -193,15 +216,12 @@ // the provenance-gated `apps_u/download_s3_file/{appPath}` endpoint; otherwise // (editor/preview) it uses the viewer-scoped `job_helpers/load_image_preview`. function s3DisplayUrl(s3object: { s3: string; storage?: string; presigned?: string }): string { - const endpoint = appPath - ? `apps_u/download_s3_file/${appPath}` - : 'job_helpers/load_image_preview' - const keyParam = appPath ? 's3' : 'file_key' - let url = `/api/w/${workspaceId}/${endpoint}?${keyParam}=${encodeURIComponent(s3object.s3)}` + if (!appPath) return s3ImagePreviewUrl(workspaceId ?? '', s3object) + let url = `/api/w/${workspaceId}/apps_u/download_s3_file/${appPath}?s3=${encodeURIComponent(s3object.s3)}` if (s3object.storage) { url += `&storage=${s3object.storage}` } - if (appPath && s3object.presigned) { + if (s3object.presigned) { url += `&${s3object.presigned}` } return url @@ -282,8 +302,12 @@ } $effect(() => { tooBigFilename = undefined + tooBigInfo = undefined const apiPath = result === 'WINDMILL_TOO_BIG' ? resultApiPath : undefined if (!apiPath) return + // The placeholder is drawn again (the view showed another result, then this one), so the + // elements loaded before are no longer shown: Load starts over from the first. + if (!untrack(() => tooBigLoaded.loading)) tooBigLoaded = { values: [], loading: false } let stale = false fetchResultAt(apiPath, 'file.filename').then( (name) => { @@ -291,19 +315,173 @@ }, () => {} ) + // `nodeId` reads a flow step's collected results, which have no row of their own. + if (workspaceId && jobId && !nodeId) { + readTooBigShape(workspaceId, jobId).then( + (shape) => { + if (!stale && shape) tooBigInfo = { apiPath, ...shape } + }, + () => {} + ) + } return () => (stale = true) }) + type ResultShape = { + type: string + length: number + keys?: string[] + item_count?: number + items?: { length: number; keys?: string[] }[] + } + /** A part of a large result: the image of an image result (read under its key and wrapped + * back), or an element of a `render_all`. */ + type TooBigPart = { + path: string + index?: number + length: number + imageKind?: string + wrap?: string + } + /** `render_all` elements read per click, and listed before the rest are counted */ + const TOO_BIG_PAGE_SIZE = 10 + const TOO_BIG_LISTED = 5 + type TooBigShape = { + length: number + /** The image of an image result, or the `render_all` elements the shape lists (the first 100) */ + parts: TooBigPart[] + /** Element count, when the result is a list or a `render_all` */ + itemCount?: number + renderAll?: boolean + } + let tooBigInfo = $state<({ apiPath: string } & TooBigShape) | undefined>(undefined) + // Read only on a click: a view is mounted for every loop iteration stepped through and every + // run card of a chat, and each would download the result. Tied to the result it was read + // from, so a new result never shows the previous one's elements. + type TooBigLoaded = { + apiPath?: string + shape?: TooBigShape + /** The `render_all` elements read so far */ + values: unknown[] + loading: boolean + } + let tooBigLoaded = $state<TooBigLoaded>({ values: [], loading: false }) + function imageKindOf(keys: string[] | undefined): string | undefined { + return keys?.length === 1 && IMG_KINDS.includes(keys[0]) ? keys[0] : undefined + } + async function fetchResultShape( + workspace: string, + id: string, + jsonPath?: string + ): Promise<ResultShape | undefined> { + const query = jsonPath ? `?json_path=${jsonPath}` : '' + const r = await fetchViaClient( + appendViewToken(`/w/${workspace}/jobs_u/completed/get_result_shape/${id}${query}`) + ) + return r.ok ? r.json() : undefined + } + async function readTooBigShape(workspace: string, id: string): Promise<TooBigShape | undefined> { + const root = await fetchResultShape(workspace, id) + if (!root) return + const rootImage = imageKindOf(root.keys) + if (rootImage) { + return { + length: root.length, + parts: [{ path: rootImage, length: root.length, imageKind: rootImage, wrap: rootImage }] + } + } + // Only a `render_all` is split into its elements, as it is drawn element by element when + // small. A bare list is drawn as a table, which needs every row, so it loads whole. + if (!(root.keys?.length === 1 && root.keys[0] === 'render_all')) { + return { + length: root.length, + parts: [], + itemCount: root.type === 'array' ? root.item_count : undefined + } + } + const list = await fetchResultShape(workspace, id, 'render_all') + // A `render_all` that is not a list, or a list whose shape could not be read, loads whole + if (list?.type !== 'array' || list.item_count === undefined) { + return { length: root.length, parts: [] } + } + const items = list.items ?? [] + return { + length: root.length, + itemCount: list.item_count, + renderAll: true, + parts: items.map((item, index) => ({ + path: `render_all.${index}`, + index, + length: item.length, + imageKind: imageKindOf(item.keys) + })) + } + } + function formatSize(chars: number): string { + return chars >= 1_000_000 + ? `${(chars / 1_000_000).toFixed(1)} MB` + : `${Math.max(1, Math.round(chars / 1000))} KB` + } + /** Size of the `render_all` elements `from` to `to`, when the shape lists them all */ + function tooBigPageSize(shape: TooBigShape, from: number, to: number): number | undefined { + if (shape.parts.length < to) return undefined + return shape.parts.slice(from, to).reduce((n, p) => n + p.length, 0) + } + /** Reads the whole result, its image, or the next page of its `render_all`, and draws what was + * read in place of the placeholder, as a result under the limit is drawn (Pretty/JSON toggle + * included). A new result from the parent wins. */ + async function loadTooBig(apiPath: string, shape: TooBigShape | undefined) { + const current: TooBigLoaded = + tooBigLoaded.apiPath === apiPath + ? tooBigLoaded + : { apiPath, shape, values: [], loading: false } + if (current.loading) return + tooBigLoaded = { ...current, loading: true } + try { + let next: unknown + let values = current.values + if (shape?.renderAll && shape.itemCount !== undefined) { + const from = values.length + const to = Math.min(shape.itemCount, from + TOO_BIG_PAGE_SIZE) + const page = await Promise.all( + Array.from({ length: to - from }, (_, i) => + fetchResultAt(apiPath, `render_all.${from + i}`) + ) + ) + values = [...values, ...page] + next = { render_all: values } + } else { + const part = shape?.parts[0] + const value = part + ? await fetchResultAt(apiPath, part.path) + : await fetchViaClient(apiPath).then((r) => { + if (!r.ok) throw new Error(`${r.status} ${r.statusText}`) + return r.json() + }) + next = part?.wrap ? { [part.wrap]: value } : value + } + if (resultApiPath !== apiPath || tooBigLoaded.apiPath !== apiPath) return + tooBigLoaded = { ...tooBigLoaded, values } + result = next + } catch (e) { + sendUserToast(`Could not load the result: ${e instanceof Error ? e.message : e}`, true) + } finally { + if (tooBigLoaded.apiPath === apiPath) tooBigLoaded = { ...tooBigLoaded, loading: false } + } + } + function base64ToBytes(content: string): Uint8Array<ArrayBuffer> { + const bin = atob(content) + // Filled byte by byte: a per-character array is several times the file's size + const bytes = new Uint8Array(bin.length) + for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i) + return bytes + } async function downloadTooBigFile(apiPath: string, name: string) { downloadingTooBigFile = true try { const content = await fetchResultAt(apiPath, 'file.content') if (typeof content !== 'string' || !content) throw new Error('the result has no file content') - const bin = atob(content) - // Filled byte by byte: a per-character array is several times the file's size - const bytes = new Uint8Array(bin.length) - for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i) // A blob, not a data: URL, which browsers cap well below a large file's size - downloadBlob(new Blob([bytes]), name) + downloadBlob(new Blob([base64ToBytes(content)]), name) } catch (e) { sendUserToast(`Download failed: ${e instanceof Error ? e.message : e}`, true) } finally { @@ -338,8 +516,14 @@ let showMaterializedPreview = $state(true) let is_render_all = $state(false) + /** `roughSizeOfObject` of the result: UTF-16 bytes, two per character. */ + let loadedResultBytes = $state(0) let download_as_csv = $state(false) function inferResultKind(result: any) { + // Reset first: the same view is reused across results (the runs page's preview), and the + // early returns below would keep a previous `render_all` or table's flags. + is_render_all = false + download_as_csv = false if (typeof result === 'string' && result.match(/s3:\/\/[^/]*\/.+/)) { largeObject = true return 's3object' @@ -377,7 +561,8 @@ // same too-big handling as any other oversized result. if (parseAgentResult(result)) { is_render_all = false - largeObject = roughSizeOfObject(result) > DISPLAY_MAX_SIZE + loadedResultBytes = roughSizeOfObject(result) + largeObject = loadedResultBytes > DISPLAY_MAX_SIZE return 'aiagent' } @@ -385,10 +570,15 @@ keys.length == 1 && keys.includes('render_all') && Array.isArray(result['render_all']) let size = roughSizeOfObject(result) + loadedResultBytes = size console.debug('size of object', size) // Otherwise, check if the result is too large (10kb) for json - if (size > TABLE_MAX_SIZE) { + // An image, file, pdf or html result is drawn whatever its size + if ( + size > TABLE_MAX_SIZE && + !(keys.length === 1 && NO_SIZE_LIMIT_KINDS.includes(keys[0])) + ) { largeObject = true if (Array.isArray(result) && isTableRowObject(result)) { download_as_csv = true @@ -535,6 +725,44 @@ return false } + const imageOpener = getImageOpener() + + /** In a session, an image result opens in the preview panel. Only a result whose job is + * known: the tab refetches it from there, and a result shown without one (a replay, a + * value an app computed) keeps expanding in place. */ + function openResultImage(format: ImageResultFormat): (() => void) | undefined { + if (!imageOpener || !jobId || !workspaceId || !resultPath) return undefined + const opener = imageOpener + const job = jobId + const workspace = workspaceId + const node = nodeId + const path = resultPath + const at = path.length ? ` #${path.filter((k) => typeof k === 'number').join('.')}` : '' + return () => + opener( + { + kind: 'result', + workspace, + jobId: job, + format, + ...(node ? { nodeId: node } : {}), + ...(path.length ? { path } : {}) + }, + (node ? `${node} result` : `Result ${job.slice(-8)}`) + at + ) + } + + function openS3Image(s3object: { + s3: string + storage?: string + presigned?: string + }): (() => void) | undefined { + if (!imageOpener) return undefined + const opener = imageOpener + const url = s3DisplayUrl(s3object) + return () => opener({ kind: 'url', url }, s3object.s3.split('/').pop() || s3object.s3) + } + function contentOrRootString(obj: string | { filename: string; content: string } | undefined) { if (obj == undefined || obj == null) { return '' @@ -834,36 +1062,79 @@ {:else if is_render_all} <div class="flex flex-col w-full gap-2"> {#if !noControls} - <div class="text-primary text-sm"> - <ToggleButtonGroup - selected={globalForceJson ? 'json' : 'pretty'} - on:selected={(ev) => { - globalForceJson = ev.detail === 'json' - }} - > - {#snippet children({ item })} - <ToggleButton value="pretty" label="Pretty" icon={Highlighter} {item} /> - <ToggleButton value="json" label="JSON" icon={Braces} {item} /> - {/snippet} - </ToggleButtonGroup> - </div> - {/if} - <div class="flex flex-col w-full gap-10"> - {#each result['render_all'] as res} - <DisplayResult - {noControls} - result={res} - {markupTrust} + <!-- Wraps, so in a narrow pane (a flow step's node panel) the toolbar takes its own line + instead of running out of the pane --> + <div class="flex flex-row flex-wrap items-center justify-between gap-2"> + <div class="text-primary text-sm"> + <ToggleButtonGroup + selected={globalForceJson ? 'json' : 'pretty'} + on:selected={(ev) => { + globalForceJson = ev.detail === 'json' + }} + > + {#snippet children({ item })} + <ToggleButton value="pretty" label="Pretty" icon={Highlighter} {item} /> + <ToggleButton value="json" label="JSON" icon={Braces} {item} /> + {/snippet} + </ToggleButtonGroup> + </div> + <DisplayResultControlBar + {customUi} {filename} - {disableExpand} + {workspaceId} {jobId} {nodeId} - {workspaceId} - {appPath} - forceJson={globalForceJson} - hideAsJson={true} + {result} + {disableTooltips} + {disableExpand} + on:open-drawer={() => openDrawer()} /> + </div> + {/if} + <!-- A size container: below 400px (a flow step's node panel) the element cards drop their + border and padding, whose width an element as wide as the pane would no longer fit in --> + <div class="flex flex-col w-full gap-3 [container-type:inline-size]"> + {#each result['render_all'] as res, i} + <!-- Drops the 160px floor a result pane keeps, so a short element hugs its content --> + <div + class="min-w-0 [@container(min-width:400px)]:rounded-md [@container(min-width:400px)]:border [@container(min-width:400px)]:p-3 [&>div]:min-h-0 [&>div>div.grow]:overflow-x-auto [&>div>div.grow]:pb-2" + > + <DisplayResult + {noControls} + result={res} + resultPath={resultPath ? [...resultPath, 'render_all', i] : null} + {markupTrust} + {filename} + {disableExpand} + {jobId} + {nodeId} + {workspaceId} + {appPath} + forceJson={globalForceJson} + hideAsJson={true} + /> + </div> {/each} + {#if tooBigLoaded.apiPath === resultApiPath && tooBigLoaded.shape?.itemCount !== undefined && tooBigLoaded.values.length < tooBigLoaded.shape.itemCount} + {@const shape = tooBigLoaded.shape} + {@const done = tooBigLoaded.values.length} + {@const next = Math.min(shape.itemCount ?? 0, done + TOO_BIG_PAGE_SIZE)} + {@const nextSize = tooBigPageSize(shape, done, next)} + <div class="flex flex-row flex-wrap items-center justify-center gap-3 py-2"> + <span class="text-xs text-secondary">{done} of {shape.itemCount} loaded</span> + <Button + variant="default" + unifiedSize="sm" + disabled={tooBigLoaded.loading} + startIcon={{ icon: tooBigLoaded.loading ? Loader2 : Eye }} + onclick={() => { + if (resultApiPath) loadTooBig(resultApiPath, shape) + }} + > + Load {next - done} more{nextSize ? ` (${formatSize(nextSize)})` : ''} + </Button> + </div> + {/if} </div> </div> {:else if resultKind === 'nondisplayable'} @@ -980,6 +1251,7 @@ <ExpandableImage alt="png rendered" class="w-auto h-full" + onOpen={openResultImage('png')} src="data:image/png;base64,{contentOrRootString(result.png)}" /> </div> @@ -988,6 +1260,7 @@ <ExpandableImage alt="jpeg rendered" class="w-auto h-full" + onOpen={openResultImage('jpeg')} src="data:image/jpeg;base64,{contentOrRootString(result.jpeg)}" /> </div> @@ -1017,6 +1290,7 @@ <ExpandableImage alt="gif rendered" class="w-auto h-full" + onOpen={openResultImage('gif')} src="data:image/gif;base64,{contentOrRootString(result.gif)}" /> </div> @@ -1111,27 +1385,48 @@ > </Alert> {/if} - {:else if !forceJson && resultKind === 'approval'}<div - class="flex flex-col gap-3 mt-2 mx-4" - > - <Button - variant="accent" - on:click={() => - fetch(result['resume'], { - method: 'POST', - body: JSON.stringify({}), - headers: { 'Content-Type': 'application/json' } - })} - > - Resume</Button - > - <Button variant="default" destructive on:click={() => fetch(result['cancel'])} - >Cancel</Button - > - <div class="center-center" - ><a rel="noreferrer" target="_blank" href={result['approvalPage']}>Approval Page</a - ></div - > + {:else if !forceJson && resultKind === 'approval'} + {@const resumeUrl = signedResumeUrl(result['resume'], 'resume', window.location.href)} + {@const cancelUrl = signedResumeUrl(result['cancel'], 'cancel', window.location.href)} + {@const approvalHref = approvalPageHref( + result['approvalPage'], + window.location.href, + resumeUrl + )} + <div class="flex flex-col gap-3 mt-2 mx-4"> + {#if resumeUrl && cancelUrl} + <Button + variant="accent" + on:click={() => + fetch(resumeUrl, { + method: 'POST', + body: JSON.stringify({}), + headers: { 'Content-Type': 'application/json' }, + credentials: resumeRequestCredentials(resumeUrl, window.location.href) + })} + > + Resume</Button + > + <Button + variant="default" + destructive + on:click={() => + fetch(cancelUrl, { + credentials: resumeRequestCredentials(cancelUrl, window.location.href) + })}>Cancel</Button + > + {/if} + {#if approvalHref} + <div class="center-center" + ><a rel="noreferrer" target="_blank" href={approvalHref}>Approval Page</a></div + > + {/if} + {#if !(resumeUrl && cancelUrl) && !approvalHref} + <span class="text-xs text-secondary" + >Resume and Cancel buttons appear for the URLs returned by getResumeUrls(); return + them unchanged.</span + > + {/if} </div> {:else if !forceJson && resultKind === 'materialized'} {@const m = parseMaterializedResult(result)} @@ -1231,24 +1526,18 @@ {/if} </div> {#if typeof s3object?.s3 === 'string'} - {#if s3object?.s3?.endsWith('.parquet') || s3object?.s3?.endsWith('.csv')} + {#if serverTableFormat(s3object.s3)} {#key s3object.s3} - <ParqetTableRenderer - disable_download={s3object?.disable_download} - {workspaceId} - {appPath} - s3resource={s3object?.s3} - storage={s3object?.storage} - presigned={s3object?.presigned} - /> + <S3ObjectTable {s3object} {workspaceId} {appPath} /> {/key} - {:else if s3object?.s3?.endsWith('.png') || s3object?.s3?.endsWith('.jpeg') || s3object?.s3?.endsWith('.jpg') || s3object?.s3?.endsWith('.webp')} + {:else if isS3ImageKey(s3object?.s3 ?? '')} <div class="h-full mt-2"> <ExpandableImage alt="preview rendered" title={s3object?.s3} class="w-auto h-full" src={s3DisplayUrl(s3object)} + onOpen={openS3Image(s3object)} /> </div> {:else if s3object?.s3?.endsWith('.pdf')} @@ -1293,16 +1582,9 @@ {:else} <div class="flex text-primary pt-2">{s3object?.s3} (download disabled)</div> {/if} - {#if s3object?.s3?.endsWith('.parquet') || s3object?.s3?.endsWith('.csv')} + {#if typeof s3object?.s3 === 'string' && serverTableFormat(s3object.s3)} {#if seeS3PreviewFileFromList == s3object?.s3} - <ParqetTableRenderer - disable_download={s3object?.disable_download} - {workspaceId} - {appPath} - s3resource={s3object?.s3} - storage={s3object?.storage} - presigned={s3object?.presigned} - />{:else} + <S3ObjectTable {s3object} {workspaceId} {appPath} />{:else} <button class="text-primary whitespace-nowrap flex gap-2 items-center" onclick={() => { @@ -1311,7 +1593,7 @@ >open table preview <ArrowDownFromLine /> </button> {/if} - {:else if s3object?.s3?.endsWith('.png') || s3object?.s3?.endsWith('.jpeg') || s3object?.s3?.endsWith('.jpg') || s3object?.s3?.endsWith('.webp')} + {:else if isS3ImageKey(s3object?.s3 ?? '')} {#if seeS3PreviewFileFromList == s3object?.s3} <div class="h-full mt-2"> <ExpandableImage @@ -1319,6 +1601,7 @@ title={s3object?.s3} class="w-auto h-full" src={s3DisplayUrl(s3object)} + onOpen={openS3Image(s3object)} /> </div> {:else} @@ -1351,6 +1634,7 @@ noControls hideAsJson result={output} + resultPath={null} {markupTrust} {filename} {disableExpand} @@ -1365,7 +1649,7 @@ {/if} {:else if !forceJson && resultKind === 'markdown'} <div class={markdownProse.sm}> - <Markdown md={result?.md ?? result?.markdown} /> + <Markdown md={result?.md ?? result?.markdown} plugins={markdownPlugins} /> </div> {:else if largeObject || hasBigInt} {#if result && typeof result === 'object' && 'file' in result} @@ -1377,50 +1661,206 @@ > </div> {:else} - {#if tooBigFilename && resultApiPath} - <div class="flex"> - <Button - onclick={() => downloadTooBigFile(resultApiPath!, tooBigFilename!)} - disabled={downloadingTooBigFile} - startIcon={{ icon: Download }} - variant="subtle" - unifiedSize="sm" - > - Download {tooBigFilename} - </Button> - </div> - {/if} {#if largeObject} - <div class="text-xs text-emphasis" - >{#if resultApiPath && shouldDownloadViaClient()} - <button onclick={() => downloadViaClient(resultApiPath!, resultDownloadName)}> - Download {filename ? '' : 'as JSON'} - </button> + {@const notSent = result === 'WINDMILL_TOO_BIG'} + {@const info = tooBigInfo?.apiPath === resultApiPath ? tooBigInfo : undefined} + {@const loaded = tooBigLoaded.apiPath === resultApiPath ? tooBigLoaded : undefined} + {@const size = notSent ? info?.length : loadedResultBytes / 2} + <!-- Not beside this component's own toolbar, whose download icon saves the same JSON. An + external toolbar may have no download (the flow output picker's mock), so it keeps it. --> + {@const toolbarDownloads = + toolbarLocation === 'self' && customUi?.disableDownload !== true} + {#snippet downloadJson(variant: 'default' | 'subtle')} + {#if resultApiPath && shouldDownloadViaClient()} + <Button + onclick={() => downloadViaClient(resultApiPath!, resultDownloadName)} + startIcon={{ icon: Download }} + {variant} + unifiedSize="sm" + > + Download JSON + </Button> {:else} - <a download={resultDownloadName} href={resultDownloadHref}> - Download {filename ? '' : 'as JSON'} - </a> + <Button + href={resultDownloadHref} + download={resultDownloadName} + startIcon={{ icon: Download }} + {variant} + unifiedSize="sm" + > + Download JSON + </Button> {/if} - {#if download_as_csv} - <DownloadCsv - getContent={() => convertJsonToCsv(result)} - customText="Download as CSV" - /> - {/if} - </div> - - <div class="mt-1 mb-2"> - <Alert - size="xs" - title="Large result detected" - type="warning" - tooltip="We recommend using persistent object storage for large result. See docs for setting up an object storage service integration using s3 or any other s3 compatible services." - documentationLink="https://www.windmill.dev/docs/core_concepts/persistent_storage#object-storage-for-large-data-s3-r2-minio-azure-blob" - /> - </div> + {/snippet} + {#if notSent} + <!-- One placeholder for any result over the limit: the elements of a `render_all`, + or the whole result as one row. Loading draws it as a result under the limit. --> + {@const parts = info?.parts ?? []} + {@const count = info?.renderAll ? (info.itemCount ?? 0) : 0} + {@const firstPage = Math.min(count, TOO_BIG_PAGE_SIZE)} + {@const loadSize = info?.renderAll ? tooBigPageSize(info, 0, firstPage) : size} + <div + class="mt-2 mb-2 rounded-md border border-dashed px-4 py-6 flex flex-col items-center gap-4" + > + {#snippet partRows(rows: TooBigPart[])} + {#each rows as part (part.path)} + {@const Icon = part.imageKind ? FileImage : Braces} + <li class="flex flex-row items-center gap-2 text-xs whitespace-nowrap"> + <Icon size={16} class="shrink-0 text-secondary" /> + <span class="font-medium text-emphasis" + >{part.imageKind ? `${part.imageKind.toUpperCase()} image` : 'JSON'}</span + > + <span class="text-secondary">{formatSize(part.length)}</span> + </li> + {/each} + {/snippet} + <ul class="flex flex-col gap-1.5"> + {#if parts.length} + {@render partRows(parts.slice(0, TOO_BIG_LISTED))} + {#if Math.max(parts.length, count) > TOO_BIG_LISTED} + {@const rest = parts.slice(TOO_BIG_LISTED)} + {@const images = rest.filter((p) => p.imageKind).length} + {@const json = rest.length - images} + <!-- The shape lists the first 100 elements: the rest are only counted --> + {@const unlisted = Math.max( + 0, + count - Math.max(parts.length, TOO_BIG_LISTED) + )} + <li class="text-xs text-secondary pl-6"> + <MeltTooltip + placement="bottom-start" + class="underline decoration-dotted cursor-default" + customBgClass="bg-surface-secondary w-56" + > + <!-- A fixed width: a box sized to its rows leaves no room for a scrollbar that + takes width, which then wraps or scrolls them sideways --> + +{[ + images ? `${images} ${images === 1 ? 'image' : 'images'}` : '', + json ? `${json} JSON` : '', + unlisted ? `${unlisted} more` : '' + ] + .filter(Boolean) + .join(', ')} + {#snippet text()} + <ul class="flex flex-col gap-1.5"> + {@render partRows(rest)} + </ul> + {/snippet} + </MeltTooltip> + </li> + {/if} + {:else} + {@const Icon = tooBigFilename + ? FileText + : info?.itemCount !== undefined + ? Brackets + : Braces} + <li class="flex flex-row items-center gap-2 text-xs whitespace-nowrap"> + <Icon size={16} class="shrink-0 text-secondary" /> + <span class="font-medium text-emphasis" + >{tooBigFilename ?? + (info?.itemCount !== undefined + ? `List of ${info.itemCount} ${info.itemCount === 1 ? 'item' : 'items'}` + : 'JSON')}</span + > + {#if size} + <span class="text-secondary">{formatSize(size)}</span> + {/if} + </li> + {/if} + </ul> + <div class="flex flex-row flex-wrap justify-center gap-2"> + <Button + variant="default" + unifiedSize="sm" + disabled={!resultApiPath || loaded?.loading} + startIcon={{ icon: loaded?.loading ? Loader2 : Eye }} + onclick={() => { + if (!resultApiPath) return + loadTooBig(resultApiPath, info) + }} + > + {count > TOO_BIG_PAGE_SIZE + ? `Load first ${TOO_BIG_PAGE_SIZE}` + : count > 1 + ? 'Load all' + : 'Load'}{loadSize ? ` (${formatSize(loadSize)})` : ''} + </Button> + {#if tooBigFilename && resultApiPath} + <Button + onclick={() => downloadTooBigFile(resultApiPath!, tooBigFilename!)} + disabled={downloadingTooBigFile} + startIcon={{ icon: Download }} + variant="subtle" + unifiedSize="sm" + > + Download + </Button> + {/if} + {#if !toolbarDownloads} + {@render downloadJson('subtle')} + {/if} + </div> + <span class="text-2xs text-secondary"> + Over the 90 KB display limit + <Tooltip + small + documentationLink="https://www.windmill.dev/docs/core_concepts/persistent_storage#object-storage-for-large-data-s3-r2-minio-azure-blob" + > + Results over 90 KB are kept with the job but not loaded with it, so they + appear here only after you click Load. + <br /><br /> + For large outputs such as images, files or big tables, we recommend workspace object + storage (S3): write the file there and return + <code>{'{ "s3": "path/to/key" }'}</code>. The job then stores only the path, + and the file is previewed right away, by type, with no Load step. + </Tooltip> + </span> + </div> + {:else} + <!-- Over DISPLAY_MAX_SIZE, a table, chart or document is drawn as this JSON tree + instead; the note says why. --> + <div class="text-2xs text-secondary mb-2"> + Shown as JSON: over 50,000 characters + <Tooltip + small + documentationLink="https://www.windmill.dev/docs/core_concepts/persistent_storage#object-storage-for-large-data-s3-r2-minio-azure-blob" + > + Results over 50,000 characters are shown as JSON rather than as a table, chart + or document. + <br /><br /> + For large outputs, we recommend workspace object storage (S3): write the file there + and return <code>{'{ "s3": "path/to/key" }'}</code>, and the file is previewed + by type. + </Tooltip> + </div> + {/if} + {#if !notSent && (download_as_csv || !toolbarDownloads)} + <div class="flex flex-row gap-2 mb-2"> + {#if download_as_csv} + <Button + onclick={() => + downloadBlob( + new Blob([convertJsonToCsv(result)], { + type: 'text/csv;charset=utf-8;' + }), + 'data.csv' + )} + startIcon={{ icon: Download }} + variant="default" + unifiedSize="sm" + > + Download CSV + </Button> + {/if} + {#if !toolbarDownloads} + {@render downloadJson('subtle')} + {/if} + </div> + {/if} {/if} {#if result && result != 'WINDMILL_TOO_BIG'} - <ObjectViewer json={result} /> + <ObjectViewer json={result} wideRows /> {/if} {/if} {:else if typeof result === 'string' && result.length > 0} @@ -1459,62 +1899,64 @@ <div class="text-primary text-xs">No result: {toJsonStr(result)}</div> {/if} </div> +{/if} - {#if !disableExpand && !noControls} - <Drawer bind:this={jsonViewer} bind:open={drawerOpen} size="900px"> - <DrawerContent title="Expanded Result" on:close={jsonViewer.closeDrawer}> - {#snippet actions()} - {#if customUi?.disableDownload !== true} - {#if resultApiPath && shouldDownloadViaClient()} - <Button - on:click={() => downloadViaClient(resultApiPath!, resultDownloadName)} - startIcon={{ icon: Download }} - variant="subtle" - unifiedSize="md" - > - Download - </Button> - {:else} - <Button - download={resultDownloadName} - href={resultDownloadHref} - startIcon={{ icon: Download }} - variant="subtle" - unifiedSize="md" - > - Download - </Button> - {/if} +<!-- Outside the result kinds above, so a `render_all` can expand too --> +{#if !disableExpand && !noControls} + <Drawer bind:this={jsonViewer} bind:open={drawerOpen} size="900px"> + <DrawerContent title="Expanded Result" on:close={jsonViewer.closeDrawer}> + {#snippet actions()} + {#if customUi?.disableDownload !== true} + {#if resultApiPath && shouldDownloadViaClient()} + <Button + on:click={() => downloadViaClient(resultApiPath!, resultDownloadName)} + startIcon={{ icon: Download }} + variant="subtle" + unifiedSize="md" + > + Download + </Button> + {:else} + <Button + download={resultDownloadName} + href={resultDownloadHref} + startIcon={{ icon: Download }} + variant="subtle" + unifiedSize="md" + > + Download + </Button> {/if} - <Button - on:click={() => copyToClipboard(toJsonStr(result))} - variant="subtle" - unifiedSize="md" - startIcon={{ - icon: ClipboardCopy - }} - > - Copy to clipboard - </Button> - {/snippet} - <DisplayResult - {noControls} - {result} - {markupTrust} - {filename} - {jobId} - {nodeId} - {workspaceId} - {appPath} - {hideAsJson} - {forceJson} - disableExpand={true} - /> - </DrawerContent> - </Drawer> + {/if} + <Button + on:click={() => copyToClipboard(toJsonStr(result))} + variant="subtle" + unifiedSize="md" + startIcon={{ + icon: ClipboardCopy + }} + > + Copy to clipboard + </Button> + {/snippet} + <DisplayResult + {noControls} + {result} + {resultPath} + {markupTrust} + {filename} + {jobId} + {nodeId} + {workspaceId} + {appPath} + {hideAsJson} + {forceJson} + disableExpand={true} + /> + </DrawerContent> + </Drawer> - <Portal name="s3filepicker"> - <S3FilePicker bind:this={s3FileViewer} readOnlyMode={true} /> - </Portal> - {/if} + <Portal name="s3filepicker"> + <S3FilePicker bind:this={s3FileViewer} readOnlyMode={true} /> + </Portal> {/if} diff --git a/frontend/src/lib/components/DisplayResultControlBar.svelte b/frontend/src/lib/components/DisplayResultControlBar.svelte index 6af502a1b8..e9b6e415f9 100644 --- a/frontend/src/lib/components/DisplayResultControlBar.svelte +++ b/frontend/src/lib/components/DisplayResultControlBar.svelte @@ -16,6 +16,7 @@ nodeId?: string | undefined result: any disableTooltips?: boolean + disableExpand?: boolean } let { @@ -25,7 +26,8 @@ jobId = undefined, nodeId = undefined, result, - disableTooltips = false + disableTooltips = false, + disableExpand = false }: Props = $props() const dispatch = createEventDispatcher() @@ -86,7 +88,9 @@ <button onclick={() => copyToClipboard(toJsonStr(result))}> <ClipboardCopy size={14} /> </button> - <button onclick={() => dispatch('open-drawer')}> - <Expand size={14} /> - </button> + {#if !disableExpand} + <button onclick={() => dispatch('open-drawer')}> + <Expand size={14} /> + </button> + {/if} </div> diff --git a/frontend/src/lib/components/DynamicInput.svelte b/frontend/src/lib/components/DynamicInput.svelte index 76395f397f..a1e7ee0e37 100644 --- a/frontend/src/lib/components/DynamicInput.svelte +++ b/frontend/src/lib/components/DynamicInput.svelte @@ -112,6 +112,15 @@ let neverLoaded = $state(true) + // Inline helper code comes from the editor, whose content can be seeded from a link: running it + // as soon as the form mounts would execute code the viewer never chose to run. Wait for the + // dropdown to be opened before loading; deployed helpers keep loading eagerly. + let openedOnce = $state(false) + $effect(() => { + if (open) openedOnce = true + }) + let canLoad = $derived(helperScript?.source !== 'inline' || open || openedOnce) + $effect(() => { if (_items.value && value !== undefined && isSelect) { if (isMultiple && Array.isArray(value) && Array.isArray(_items.value)) { @@ -175,6 +184,7 @@ ;[filterText, entrypoint, helperScript] if ( resultJobLoader && + canLoad && (open || neverLoaded || !deepEqual(filterArgs(lastArgs), filterArgs(nargs))) ) { neverLoaded = false @@ -193,6 +203,7 @@ bind:value items={safeSelectItems(items || [])} placeholder="Select items" + onOpen={() => (openedOnce = true)} noItemsMsg={_items.status === 'loading' ? 'Loading...' : 'No items found'} disabled={disabled || _items.status === 'loading'} /> diff --git a/frontend/src/lib/components/Editor.svelte b/frontend/src/lib/components/Editor.svelte index da930c03f4..b1d350c9fe 100644 --- a/frontend/src/lib/components/Editor.svelte +++ b/frontend/src/lib/components/Editor.svelte @@ -36,6 +36,7 @@ type DBSchema, codeCompletionSessionEnabled, lspTokenStore, + needsSuperAdminFor, formatOnSave, vimMode, relativeLineNumbers @@ -112,10 +113,12 @@ import { editorPositionMap } from '$lib/utils' import { extToLang, langToExt } from '$lib/editorLangUtils' import { aiChatManager, type AIChatManager } from './copilot/chat/AIChatManager.svelte' - import type { Selection } from 'monaco-editor' import { canHavePreprocessor, getPreprocessorModuleCode } from '$lib/script_helpers' import { setMonacoTypescriptOptions } from './monacoLanguagesOptions' import { copilotInfo } from '$lib/aiStore' + import { createCodeSelection, type CodeSelection, type CodeSource } from './copilot/chat/context' + import { getOpenInSessionHandoff, withEditorFlush } from './sessions/openInSessionContext' + import { openSourceInSession } from './sessions/sessionSwitch.svelte' import { getDbSchemas } from './apps/components/display/dbtable/metadata' import { rawAppLintStore, type MonacoLintError } from './raw_apps/lintStore' import { MarkerSeverity } from 'monaco-editor' @@ -168,7 +171,10 @@ loadAsync?: boolean key?: string | undefined class?: string | undefined - moduleId?: string + /** The item an AI session is told the selected code belongs to. Unset for code of no item. */ + codeSource?: CodeSource + /** The language an AI session is told the code is in, when `scriptLang` only colours it. */ + codeSourceLang?: CodeSelection['lang'] enablePreprocessorSnippet?: boolean /** When set, enables raw app lint collection mode and reports Monaco markers to the lint store under this key */ rawAppRunnableKey?: string | undefined @@ -210,7 +216,8 @@ loadAsync = false, key = undefined, class: clazz = undefined, - moduleId = undefined, + codeSource = undefined, + codeSourceLang = undefined, enablePreprocessorSnippet = false, rawAppRunnableKey = undefined, preparedAssetsSqlQueries, @@ -282,6 +289,22 @@ const completionInfo = $derived( sessionScopedChatManager ? sessionScopedChatManager.aiInfo : $copilotInfo ) + const sessionHandoff = getOpenInSessionHandoff() + const inIframe = BROWSER && window.self !== window.top + // The item's own hand-off: one of another kind is an outer editor's. + const handoffSource = $derived.by(() => { + if (!codeSource) return undefined + const source = sessionHandoff?.source( + codeSource.kind === 'flow' ? { moduleId: codeSource.part } : undefined + ) + return source?.target?.kind === codeSource.kind ? source : undefined + }) + // The path the item's draft is stored under, which the session's tools read it by. + const codePath = $derived(handoffSource?.target?.path || codeSource?.path) + // In a session, ⌘K goes to its chat instead. + const newSessionSource = $derived( + sessionScopedChatManager || inIframe || !$copilotInfo.enabled ? undefined : handoffSource + ) // let graphqlService: MonacoGraphQLAPI | undefined = undefined let fetchedDbSchema: DBSchema | undefined = $state(undefined) @@ -398,18 +421,56 @@ } } - export function getSelectedLines(): string | undefined { - if (editor) { - const selection = editor.getSelection() - if (selection) { - const range: IRange = { - startLineNumber: selection.startLineNumber, + /** The selected lines, whole, or the cursor's line. */ + function getCodeSelection(): CodeSelection | undefined { + const selection = editor?.getSelection() + const model = editor?.getModel() + if (!selection || !model || !codeSource || !codePath || !scriptLang) return undefined + const { startLineNumber: startLine, endLineNumber, endColumn } = selection + // A selection dragged to the start of a line holds none of it. + const endLine = + endColumn === 1 && endLineNumber > startLine ? endLineNumber - 1 : endLineNumber + return createCodeSelection( + { ...codeSource, path: codePath }, + { + startLine, + endLine, + content: model.getValueInRange({ + startLineNumber: startLine, startColumn: 1, - endLineNumber: selection.endLineNumber + 1, - endColumn: 1 - } - return editor.getModel()?.getValueInRange(range) + endLineNumber: endLine, + endColumn: model.getLineMaxColumn(endLine) + }), + lang: codeSourceLang ?? (scriptLang as CodeSelection['lang']) } + ) + } + + async function sendInlinePrompt(prompt: string): Promise<boolean> { + const selection = getCodeSelection() + if (!selection || !newSessionSource) return false + try { + await openSourceInSession(withEditorFlush(newSessionSource, flushPendingChanges), { + seedPrompt: prompt, + autoSend: true, + seedPick: selection + }) + } catch (e) { + sendUserToast(e instanceof Error ? e.message : String(e), true) + return false + } + closeAIInlineWidget() + return true + } + + /** Go to the session's chat, with the selected lines. Outside a session no chat is on screen. */ + function attachSelectionToChat() { + if (!sessionScopedChatManager) return + const selection = editor?.getSelection()?.isEmpty() ? undefined : getCodeSelection() + if (selection) { + sessionScopedChatManager.attachCodeSelection(selection) + } else { + sessionScopedChatManager.focusInput() } } @@ -982,8 +1043,6 @@ // Inline ai chat widget let showInlineAIChat = $state(false) - let inlineAIChatSelection: Selection | null = $state(null) - let selectedCode = $state('') export async function reviewAndApplyCode(code: string, opts?: ReviewChangesOpts) { await aiChatEditorHandler?.reviewChanges(code, opts) @@ -1618,9 +1677,6 @@ editor?.addCommand(KeyMod.CtrlCmd | KeyCode.DownArrow, function () { if (aiChatManager.pendingNewCode) { aiChatManager.scriptEditorApplyCode?.(aiChatManager.pendingNewCode) - if (showInlineAIChat) { - closeAIInlineWidget() - } } }) @@ -1649,35 +1705,16 @@ }) editor?.addCommand(KeyMod.CtrlCmd | KeyCode.KeyL, function () { - const selectedLines = getSelectedLines() - const selection = editor?.getSelection() - const hasSelection = - selection && - (selection.startLineNumber !== selection.endLineNumber || - selection.startColumn !== selection.endColumn) - // Only a session pane has a chat on screen to send the lines to. - const chat = sessionScopedChatManager - if (!chat) return - if (hasSelection && selectedLines) { - chat.addSelectedLinesToContext( - selectedLines, - selection.startLineNumber, - selection.endLineNumber, - moduleId - ) - } else { - chat.focusInput() - } + // Monaco runs a command for whichever editor has focus, this one or not. + if (editor?.hasWidgetFocus()) attachSelectionToChat() }) editor?.addCommand(KeyMod.CtrlCmd | KeyCode.KeyK, function () { - if ($copilotInfo.enabled) { - aiChatEditorHandler?.rejectAll() - if (showInlineAIChat) { - closeAIInlineWidget() - } else { - showAIInlineWidget() - } + if (!editor?.hasWidgetFocus()) return + if (newSessionSource) { + showInlineAIChat = !showInlineAIChat + } else { + attachSelectionToChat() } }) @@ -1896,30 +1933,10 @@ }) } - function showAIInlineWidget() { - if (!editor) return - - inlineAIChatSelection = editor.getSelection() - if (!inlineAIChatSelection) { - return - } - const model = editor.getModel() - selectedCode = '' - if (model) { - selectedCode = model.getValueInRange(inlineAIChatSelection) - } - showInlineAIChat = true - aiChatInlineWidget?.focusInput() - } - function closeAIInlineWidget() { showInlineAIChat = false - inlineAIChatSelection = null - selectedCode = '' } - let aiChatInlineWidget: AIChatInlineWidget | null = $state(null) - $effect(() => { const fontSize = small ? editorFontSize.small : editorFontSize.regular if (editor) { @@ -1968,14 +1985,23 @@ }) async function genRoot(hostname: string) { - let token = $lspTokenStore + const workspace = $operatingWorkspace ?? '' + const cached = $lspTokenStore + let token = cached?.workspace === workspace ? cached.token : undefined if (!token) { let expiration = new Date() expiration.setHours(expiration.getHours() + 72) const newToken = await UserService.createToken({ - requestBody: { label: 'Ephemeral lsp token', expiration: expiration.toISOString() } + requestBody: { + label: 'Ephemeral lsp token', + expiration: expiration.toISOString(), + workspace_id: workspace || undefined, + // It reads the scripts an import names as the editing user would, admin included. + admin: true, + super_admin: needsSuperAdminFor(workspace) + } }) - $lspTokenStore = newToken + $lspTokenStore = { workspace, token: newToken } token = newToken } let root = hostname + '/api/scripts_u/tokened_raw/' + $operatingWorkspace + '/' + token @@ -2008,9 +2034,6 @@ rejectCodeChanges() } else if ((e.ctrlKey || e.metaKey) && e.key === 'ArrowDown' && aiChatManager.pendingNewCode) { acceptCodeChanges() - if (showInlineAIChat) { - closeAIInlineWidget() - } } } $effect(() => { @@ -2250,14 +2273,15 @@ <GlobalReviewButtons onAcceptAll={acceptCodeChanges} onRejectAll={rejectCodeChanges} /> {/if} -{#if editor && $copilotInfo.enabled && aiChatEditorHandler} +{#if editor && showInlineAIChat && newSessionSource} <AIChatInlineWidget - bind:this={aiChatInlineWidget} - bind:show={showInlineAIChat} {editor} - editorHandler={aiChatEditorHandler} - selection={inlineAIChatSelection} - {selectedCode} + line={editor.getSelection()?.startLineNumber ?? 1} + onSend={sendInlinePrompt} + onClose={(refocus) => { + closeAIInlineWidget() + if (refocus) editor?.focus() + }} /> {/if} diff --git a/frontend/src/lib/components/FilterSearchbar.svelte b/frontend/src/lib/components/FilterSearchbar.svelte index 76c0fa1cdb..9475881663 100644 --- a/frontend/src/lib/components/FilterSearchbar.svelte +++ b/frontend/src/lib/components/FilterSearchbar.svelte @@ -417,11 +417,14 @@ let highlightedIndex = $state(0) let taggedTextInput: TaggedTextInput | undefined = $state() + // A key is letters, digits and `_` in any script; `\b` and `\w` only know ASCII ones. + const KEY_START = '(?<![\\p{L}\\p{N}_])' + let tags = $derived( Object.entries(schema) .filter(([_, s]) => !s.hidden) .map(([key, filterSchema]) => ({ - regex: new RegExp(`\\b${key}:(?:\\\\.|[^\\s])*`, 'g'), + regex: new RegExp(`${KEY_START}${key}:(?:\\\\.|[^\\s])*`, 'gu'), id: key, onClear: () => (delete value[key], asText.reparse()) })) @@ -429,18 +432,18 @@ let keyHighlightRegex = $derived( new RegExp( - `\\b(${Object.entries(schema) + `${KEY_START}(${Object.entries(schema) .filter(([_, s]) => !s.hidden) .map(([k]) => k) .join('|')}):`, - 'g' + 'gu' ) ) let errorKeys = $derived(new Set(errors.flatMap((e) => e.fields))) let errorHighlights = $derived( [...errorKeys].map((key) => ({ - regex: new RegExp(`(?<=\\b${key}:)(?:\\\\.|[^\\s])+`), + regex: new RegExp(`(?<=${KEY_START}${key}:)(?:\\\\.|[^\\s])+`, 'u'), classes: 'text-red-500 dark:text-red-400' })) ) @@ -568,7 +571,7 @@ highlightedIndex = 0 }) - const kvRegex = /\b(\w+):((?:[^\s\\]|\\.)*)/g + const kvRegex = new RegExp(`${KEY_START}([\\p{L}\\p{N}_]+):((?:[^\\s\\\\]|\\\\.)*)`, 'gu') function parseFromText(text: string): Partial<FilterInstanceRec<SchemaT>> { const parsed: Record<string, string> = {} @@ -812,7 +815,16 @@ {autofocus} /> {#if asText.val} - <CloseButton small class="mr-1.5" onClick={() => (_value.current = {})} /> + <CloseButton + small + class="mr-1.5" + onClick={() => { + _value.current = {} + // On a closed bar this click's mousedown just wrote the text, and the text skips the + // filter change that follows its own write: left to that sync, the old text stays. + asText.reparse() + }} + /> {:else if searchIconPosition === 'right'} <div class="mr-3"> <SearchIcon size={16} class="text-hint" /> diff --git a/frontend/src/lib/components/FlowBuilder.svelte b/frontend/src/lib/components/FlowBuilder.svelte index 6a545423f8..b0c2e57b8b 100644 --- a/frontend/src/lib/components/FlowBuilder.svelte +++ b/frontend/src/lib/components/FlowBuilder.svelte @@ -138,6 +138,7 @@ import { editInForkAllowed, editInForkLabel, openEditInFork } from '$lib/utils/editInFork' import { isCloudHosted } from '$lib/cloud' import { UserDraft } from '$lib/userDraft.svelte' + import { assertDraftSaved } from './sessions/pageDrawerSession' import { setOpenInSessionHandoff } from './sessions/openInSessionContext' import { getEditorStoragePath, setEditorStoragePath } from './editorStoragePathContext' import { useEditRights, useRoleCapabilities, useTriggerLock } from '$lib/operatorWriteRights' @@ -494,9 +495,15 @@ // discardIf baseline, safe only when there is none. async function persistDraftForSession(): Promise<void> { await saveDraft() - if (opWorkspace && liveEditorDraftStoragePath && newFlow) { + if (!opWorkspace || !liveEditorDraftStoragePath) return + if (newFlow) { await UserDraft.forcePersist('flow', liveEditorDraftStoragePath, { workspace: opWorkspace }) } + assertDraftSaved({ + workspace: opWorkspace, + itemKind: 'flow', + path: liveEditorDraftStoragePath + }) } export function computeUnlockedSteps(flow: Flow) { @@ -1034,18 +1041,16 @@ const outerStoragePath = getEditorStoragePath() setEditorStoragePath(() => liveEditorDraftStoragePath ?? outerStoragePath?.()) - // "Open in AI session" target: the URL draft path the editor loads/saves by - // (which for a new flow differs from the live-edited friendly `$pathStore`), - // falling back to `$pathStore` in drawer mounts that carry no storage path. - const sessionTargetPath = $derived(liveEditorDraftStoragePath || $pathStore) - const aiBuilderShown = $derived(!disableAi && customUi?.topBar?.aiBuilder != false) const showFlowAiButton = $derived(aiBuilderShown && $roleCaps.flows !== 'compose') + // Targets the draft path the editor loads/saves by, which for a new flow differs from + // the live-edited friendly `$pathStore`. A drawer mount has none: its edits are in no + // draft, so leaving for a session would lose them. const sessionOpen = $derived( - sessionTargetPath + indicatorPath ? { - target: { kind: 'flow' as const, path: sessionTargetPath }, + target: { kind: 'flow' as const, path: indicatorPath }, workspaceId: opWorkspace ?? undefined, beforeOpen: persistDraftForSession } diff --git a/frontend/src/lib/components/FlowPreviewContent.svelte b/frontend/src/lib/components/FlowPreviewContent.svelte index 3500d10390..6f7ff1296f 100644 --- a/frontend/src/lib/components/FlowPreviewContent.svelte +++ b/frontend/src/lib/components/FlowPreviewContent.svelte @@ -632,7 +632,15 @@ </div> {#if jobId} - <FlowProgressBar {job} bind:this={flowProgressBar} slim textPosition="bottom" showStepId /> + <FlowProgressBar + {job} + bind:this={flowProgressBar} + slim + textPosition="bottom" + showStepId + stepStates={localModuleStates} + waitingNested={Object.keys(suspendStatus?.val ?? {}).length > 0} + /> {/if} {#if job} diff --git a/frontend/src/lib/components/FlowRestartButton.svelte b/frontend/src/lib/components/FlowRestartButton.svelte index 073360b4c4..119b8668d6 100644 --- a/frontend/src/lib/components/FlowRestartButton.svelte +++ b/frontend/src/lib/components/FlowRestartButton.svelte @@ -385,7 +385,9 @@ <ToggleButton value="failed" label="Failed only{failedCount ? ` (${failedCount})` : ''}" - tooltip="Keep the results that succeeded and rerun the failed ones from their first step, each in its original position" + tooltip="Keep the results that succeeded and rerun the failed ones {fromFailedStep + ? 'from the step where each failed' + : 'from their first step'}, each in its original position" showTooltipIcon disabled={failedCount === 0} {item} diff --git a/frontend/src/lib/components/FlowStatusViewer.svelte b/frontend/src/lib/components/FlowStatusViewer.svelte index 75c881fdc6..e0ba599727 100644 --- a/frontend/src/lib/components/FlowStatusViewer.svelte +++ b/frontend/src/lib/components/FlowStatusViewer.svelte @@ -97,13 +97,11 @@ let lastJobId: string = untrack(() => jobId) - let retryStatus = $state({ val: {} }) let globalRefreshes: Record<string, ((clear, root) => Promise<void>)[]> = $state({}) setContext<FlowStatusViewerContext>('FlowStatusViewer', { flowState, suspendStatus, - retryStatus, hideDownloadInGraph: untrack(() => hideDownloadInGraph), hideNodeDefinition: untrack(() => hideNodeDefinition), hideTimeline: untrack(() => hideTimeline), @@ -119,7 +117,6 @@ if (jobId !== lastJobId) { console.log('updateJobId 3', jobId) lastJobId = jobId - retryStatus.val = {} suspendStatus.val = {} globalRefreshes = {} for (let key in localModuleStates) delete flowState[key] @@ -152,10 +149,17 @@ let storedToolCallJobs: Record<string, Job> = $state({}) let toolCallIndicesToLoad: string[] = $state([]) + + let inner: FlowStatusViewerInner | undefined = $state(undefined) + /** Selects a step in the graph, as a click on its node does. */ + export function selectStep(id: string) { + inner?.selectStep(id) + } </script> {#key jobId} <FlowStatusViewerInner + bind:this={inner} onJobsLoaded={({ job, force }) => { if (job.script_path != lastScriptPath && job.script_path) { lastScriptPath = job.script_path diff --git a/frontend/src/lib/components/FlowStatusViewerInner.svelte b/frontend/src/lib/components/FlowStatusViewerInner.svelte index 9d00cd87c4..aab0b5c801 100644 --- a/frontend/src/lib/components/FlowStatusViewerInner.svelte +++ b/frontend/src/lib/components/FlowStatusViewerInner.svelte @@ -13,8 +13,10 @@ type CompletedJob, type WorkflowStatus, type FlowNote, - type FlowValue + type FlowValue, + ConcurrencyGroupsService } from '$lib/gen' + import { getDbClockNow } from '$lib/forLater' import FlowJobResult from './FlowJobResult.svelte' import WorkflowTimeline from './WorkflowTimeline.svelte' import DisplayResult from './DisplayResult.svelte' @@ -84,7 +86,6 @@ let { flowState: flowStateStore, - retryStatus, suspendStatus, hideDownloadInGraph, hideTimeline, @@ -348,6 +349,49 @@ let selectionManager = new SelectionManager() + function onGraphSelect(e: string | FlowModule) { + subflowPathChain = undefined + if (rightColumnSelect != 'node_definition' && rightColumnSelect != 'tracing') { + rightColumnSelect = 'node_status' + } + if (typeof e == 'string') { + if (e == 'Input') { + selectedNode = 'start' + stepDetail = undefined + } else if (e == 'Result') { + selectedNode = 'end' + stepDetail = 'end' + } else { + const id = e.startsWith(AI_TOOL_CALL_PREFIX) ? e.split('-').pop() : e + const resolved = resolveLoadedExpandedSubflowStep( + e, + job?.raw_flow?.modules ?? [], + expandedSubflows ?? {} + ) + stepDetail = + resolved?.module ?? dfs(job?.raw_flow?.modules ?? [], (m) => m).find((m) => m?.id === id) + subflowPathChain = resolved?.pathChain + selectedNode = e + if (e.startsWith(AI_TOOL_CALL_PREFIX)) { + const [_prefix, agentModuleId, j, _toolModuleId] = e.split('-') + const parentLoopsPrefix = getParentLoopsPrefix(agentModuleId) + const jIdx = Number(j) + const storeKey = parentLoopsPrefix + agentModuleId + '-' + jIdx + toolCallStore?.addToolCallToLoad(storeKey) + } + } + } else { + stepDetail = e + selectedNode = e.id + } + } + + /** Selects a step from outside the graph, as a click on its node does. */ + export function selectStep(id: string) { + selectionManager.selectId(id) + onGraphSelect(id) + } + function onFlowModuleId() { let modId = flowJobIds?.moduleId if (modId) { @@ -588,21 +632,10 @@ } updateInnerModules(status) - // The preprocessor (step -1) and the error handler (past the steps) retry outside `modules`. - const outsideSteps = status.step < 0 || status.step >= status.modules.length - let count = - job?.type === 'CompletedJob' || (retryingStepId == undefined && !outsideSteps) - ? undefined - : status.retry?.fail_count - if (count) { - retryStatus.val[jobId ?? ''] = count - } else if (retryStatus.val[jobId ?? ''] != undefined) { - delete retryStatus.val[jobId ?? ''] - } let jobStatus = job?.flow_status?.modules?.[job?.flow_status.step] if (jobStatus && jobStatus.count != undefined) { - suspendStatus.val[jobId ?? ''] = { nb: jobStatus.count, job: job! } + suspendStatus.val[jobId ?? ''] = { nb: jobStatus.count, job: job!, prefix } } else if (suspendStatus.val[jobId ?? ''] != undefined) { delete suspendStatus.val[jobId ?? ''] } @@ -682,6 +715,94 @@ /** The step waiting for or running its next attempt, if any. */ let retryingStepId: string | undefined = undefined + + // A concurrency limit moves a waiting step's due time each time it holds it back, often by + // only a few seconds, so a step still waiting once that time has passed is read again, at + // most every 5s. The parent flow does not change meanwhile, hence the timer below. + const waitingStepChecks = new Map<string, number>() + // A step's concurrency key is written as it is queued: one without can never be held, so + // past the end of its sleep only a change of the parent flow can change what it waits for. + const unlimitedSteps = new Set<string>() + function waitingStepDue(mod: FlowStatusModule): boolean { + const last = waitingStepChecks.get(mod.job ?? '') + if (last != undefined && Date.now() - last < 5000) return false + const scheduledFor = localModuleStates[mod.id ?? '']?.scheduled_for + return scheduledFor == undefined || new Date(scheduledFor) <= getDbClockNow() + } + + function loadWaitingStep(mod: FlowStatusModule, retrying: boolean) { + waitingStepChecks.set(mod.job ?? '', Date.now()) + const workspace = workspaceId ?? $operatingWorkspace ?? '' + Promise.all([ + JobService.getJob({ workspace, id: mod.job ?? '', noLogs: true, noCode: true }), + ConcurrencyGroupsService.getConcurrencyKeyStatus({ id: mod.job ?? '' }).catch(() => undefined) + ]) + .then(([job, held]) => { + // The step may have started or ended while this was in flight. + const now = innerModules?.find((m) => m.id === mod.id) + if (now?.type !== 'WaitingForExecutor' || now.job !== mod.job) return + if (held === null) unlimitedSteps.add(mod.job ?? '') + const scheduledFor: string | undefined = job?.['scheduled_for'] + // Once let in, a held job only waits for a worker. + const waiting_reason: GraphModuleState['waiting_reason'] = + held?.deferred_from && !held.released_at + ? 'concurrency' + : scheduledFor && + new Date(scheduledFor) > getDbClockNow() && + !retrying && + sleepsBefore(mod.id) + ? 'sleep' + : undefined + setModuleState(mod.id ?? '', { + type: mod.type, + scheduled_for: job?.['scheduled_for'], + waiting_reason, + concurrency_key: waiting_reason === 'concurrency' ? held?.key : undefined, + held_since: + waiting_reason === 'concurrency' ? (held?.deferred_from ?? undefined) : undefined, + job_id: job?.id, + parent_module: failedStepOf(mod), + args: job?.args, + tag: job?.tag, + script_hash: job?.script_hash + }) + // So the timeline draws the wait while it lasts. + if (waiting_reason && job?.created_at) + setDurationStatusByJob( + mod.id ?? '', + job.id, + { created_at: new Date(job.created_at).getTime() }, + true + ) + }) + .catch((e) => { + console.error(`Could not load inner module for job ${mod.job}`, e) + }) + } + + $effect(() => { + if (job?.type !== 'QueuedJob' || isReplay) return + const id = setInterval(() => { + innerModules?.forEach((mod) => { + if ( + mod.type === 'WaitingForExecutor' && + (!unlimitedSteps.has(mod.job ?? '') || + localModuleStates[mod.id ?? '']?.waiting_reason === 'sleep') && + waitingStepDue(mod) + ) { + loadWaitingStep(mod, mod.id === retryingStepId) + } + }) + }, 5000) + return () => clearInterval(id) + }) + + /** Whether the step before `id` sleeps once done, which pushes `id` back by that long. */ + function sleepsBefore(id: string | undefined): boolean { + const raw = job?.raw_flow?.modules ?? [] + const i = raw.findIndex((m) => m.id === id) + return i > 0 && !!raw[i - 1].sleep + } function updateInnerModules(status: FlowStatus) { const found = findDeniedApproval(status) const denied = found?.approval @@ -707,6 +828,24 @@ if (mod.type === 'Failure' && localModuleStates[mod.id ?? '']?.type === 'Success') { setModuleState(mod.id ?? '', { type: 'Failure' }) } + // The step after an approval step is the one that waits for it. + const approvalStep = innerModules?.[i - 1] + const approvalWait = + mod.id && + job?.id && + approvalStep?.id && + approvalStep.type === 'Success' && + mod.type === 'WaitingForEvents' + ? { + job: job.id, + workspace: job.workspace_id, + step: approvalStep.id, + required: mod.count ?? 1 + } + : undefined + if (mod.id && !deepEqual(approvalWait, localModuleStates[mod.id]?.approval_wait)) { + setModuleState(mod.id, { approval_wait: approvalWait }) + } if (mod.type === 'WaitingForEvents' && innerModules?.[i - 1]?.type === 'Success') { setModuleState(mod.id ?? '', { type: mod.type, @@ -714,33 +853,9 @@ tag: job?.tag, script_hash: job?.script_hash }) - } else if ( - mod.type === 'WaitingForExecutor' && - localModuleStates[mod.id ?? '']?.scheduled_for == undefined - ) { + } else if (mod.type === 'WaitingForExecutor' && waitingStepDue(mod)) { if (!isReplay) { - JobService.getJob({ - workspace: workspaceId ?? $operatingWorkspace ?? '', - id: mod.job ?? '', - noLogs: true, - noCode: true - }) - .then((job) => { - const newState = { - type: mod.type, - scheduled_for: job?.['scheduled_for'], - job_id: job?.id, - parent_module: failedStepOf(mod), - args: job?.args, - tag: job?.tag, - script_hash: job?.script_hash - } - - setModuleState(mod.id ?? '', newState) - }) - .catch((e) => { - console.error(`Could not load inner module for job ${mod.job}`, e) - }) + loadWaitingStep(mod, mod.id === retryingId) } } else if ( (mod.flow_jobs || mod.branch_chosen) && @@ -1372,8 +1487,6 @@ let wrapperHeight: number = $state(0) - let retryStatusHeight: number = $state(0) - function removeFailureNode(id: string, parent_module: any) { if (id?.startsWith('failure-') && parent_module) { ;[...globalModuleStates, localModuleStates].forEach((stateMap) => { @@ -1394,12 +1507,33 @@ suspend?: boolean /** Shown in place of the id. */ label?: string + /** The fixed sleep of the step before it, in seconds. */ + sleepBefore?: number + /** An inline script with a concurrency limit, which can be held back. */ + limited?: boolean + } + + // Sleeps in branches and loop bodies are not looked at. + function timelineExtras( + modules: FlowModule[] + ): Map<string, { sleepBefore?: number; limited?: boolean }> { + const extras = new Map<string, { sleepBefore?: number; limited?: boolean }>() + modules.forEach((m, i) => { + const sleep = modules[i - 1]?.sleep + const v = m.value + extras.set(m.id, { + sleepBefore: sleep?.type === 'static' ? Number(sleep.value) || undefined : undefined, + limited: v.type === 'rawscript' && (v.concurrent_limit ?? 0) > 0 + }) + }) + return extras } function allModulesForTimeline( modules: FlowModule[], expandedSubflows: Record<string, { modules: FlowModule[]; groups?: any[] }> ): FlowModuleForTimeline[] { + const topExtras = timelineExtras(modules) const ids = dfs( modules, (x) => @@ -1407,7 +1541,8 @@ id: x.id, type: x.value.type, suspend: x.suspend != undefined, - label: x.id === AGENT_STEP_ID ? agentStepLabel(job?.script_path) : undefined + label: x.id === AGENT_STEP_ID ? agentStepLabel(job?.script_path) : undefined, + ...topExtras.get(x.id) }) as FlowModuleForTimeline, { skipToolNodes: true @@ -1426,6 +1561,7 @@ return [] } let nprefix = buildPrefix(prefix, oid) + const extras = fms ? timelineExtras(fms) : undefined return fms ? rec( dfs( @@ -1433,7 +1569,8 @@ (x) => ({ id: x.id.startsWith('subflow:') ? x.id : buildSubflowKey(x.id, nprefix), type: x.value.type, - suspend: x.suspend != undefined + suspend: x.suspend != undefined, + ...extras?.get(x.id) }), { skipToolNodes: true } ), @@ -1612,10 +1749,6 @@ ) ) - let totalEventsWaiting = $derived( - Object.values(suspendStatus?.val ?? {}).reduce((a, b) => a + (b?.nb ?? 0), 0) - ) - let continuedOnError = $derived(job?.flow_status?.continued_on_error ?? []) </script> @@ -2094,6 +2227,10 @@ <ModuleStatus type={mod.type} scheduled_for={localModuleStates?.[mod.id ?? '']?.scheduled_for} + waiting_reason={localModuleStates?.[mod.id ?? '']?.waiting_reason} + concurrency_key={localModuleStates?.[mod.id ?? '']?.concurrency_key} + held_since={localModuleStates?.[mod.id ?? '']?.held_since} + approval_wait={localModuleStates?.[mod.id ?? '']?.approval_wait} /> {/if} </li> @@ -2167,69 +2304,19 @@ <Splitpanes> <Pane bind:size={graphPaneSize} minSize={30}> <div class="bg-surface-secondary h-full {fillHeight ? '' : 'max-h-[1200px]'}"> - <div class="flex flex-col" bind:clientHeight={retryStatusHeight}> - {#each Object.values(retryStatus?.val ?? {}) as count} - {#if count} - <span class="text-sm"> - Retry in progress, # of failed attempts: {count} - </span> - {/if} - {/each} - {#if totalEventsWaiting} - <span class="text-sm"> - Flow suspended, waiting for {totalEventsWaiting} events - </span> - {/if} - </div> <FlowGraphV2 {selectionManager} triggerNode={true} download={!hideDownloadInGraph} - minHeight={wrapperHeight - retryStatusHeight} - maxHeight={fillHeight ? wrapperHeight - retryStatusHeight : undefined} + minHeight={wrapperHeight} + maxHeight={fillHeight ? wrapperHeight : undefined} fitOnLoad={fillHeight} outerDivClass={fillHeight ? '' : 'max-h-[1200px]'} success={jobId != undefined && isSuccess(job?.['success'])} flowModuleStates={localModuleStates} runDone={job?.type === 'CompletedJob'} bind:expandedSubflows - onSelect={(e) => { - subflowPathChain = undefined - if (rightColumnSelect != 'node_definition' && rightColumnSelect != 'tracing') { - rightColumnSelect = 'node_status' - } - if (typeof e == 'string') { - if (e == 'Input') { - selectedNode = 'start' - stepDetail = undefined - } else if (e == 'Result') { - selectedNode = 'end' - stepDetail = 'end' - } else { - const id = e.startsWith(AI_TOOL_CALL_PREFIX) ? e.split('-').pop() : e - const resolved = resolveLoadedExpandedSubflowStep( - e, - job?.raw_flow?.modules ?? [], - expandedSubflows ?? {} - ) - stepDetail = - resolved?.module ?? - dfs(job?.raw_flow?.modules ?? [], (m) => m).find((m) => m?.id === id) - subflowPathChain = resolved?.pathChain - selectedNode = e - if (e.startsWith(AI_TOOL_CALL_PREFIX)) { - const [_prefix, agentModuleId, j, _toolModuleId] = e.split('-') - const parentLoopsPrefix = getParentLoopsPrefix(agentModuleId) - const jIdx = Number(j) - const storeKey = parentLoopsPrefix + agentModuleId + '-' + jIdx - toolCallStore?.addToolCallToLoad(storeKey) - } - } - } else { - stepDetail = e - selectedNode = e.id - } - }} + onSelect={onGraphSelect} {onSelectedIteration} earlyStop={job.raw_flow?.skip_expr !== undefined} cache={job.raw_flow?.cache_ttl !== undefined} @@ -2443,6 +2530,10 @@ <ModuleStatus type={node.type} scheduled_for={node.scheduled_for} + waiting_reason={node.waiting_reason} + concurrency_key={node.concurrency_key} + held_since={node.held_since} + approval_wait={node.approval_wait} skipped={node.skipped} /> {#if node.duration_ms} diff --git a/frontend/src/lib/components/FlowStatusWaitingForEvents.svelte b/frontend/src/lib/components/FlowStatusWaitingForEvents.svelte index 9c8c3625c3..cd5edd3f7a 100644 --- a/frontend/src/lib/components/FlowStatusWaitingForEvents.svelte +++ b/frontend/src/lib/components/FlowStatusWaitingForEvents.svelte @@ -96,6 +96,23 @@ <DisplayResult {workspaceId} noControls result={description} language={job?.language} /> <div class="mt-2"></div> {/if} + <!-- The form first, then its buttons below it, as any form is submitted. --> + {#if job?.raw_flow?.modules?.[approvalStep]?.suspend?.resume_form?.schema} + <div class="flex items-start gap-1 mb-2"> + <div + class={twMerge( + 'w-full border rounded-lg p-2', + light ? 'min-w-96 max-h-svh overflow-y-auto' : '' + )} + > + <SchemaForm onlyMaskPassword bind:args={default_payload} {defaultValues} {schema} /> + </div> + <Tooltip> + The payload is optional, it is passed to the following step through the `resume` + variable + </Tooltip> + </div> + {/if} <!-- A new approval step gets usable buttons again. --> {#key job?.flow_status?.modules?.[approvalStep]?.job} <ApprovalActions @@ -118,20 +135,6 @@ </a> {/if} - {#if job?.raw_flow?.modules?.[approvalStep]?.suspend?.resume_form?.schema} - <div - class={twMerge( - 'w-full border rounded-lg p-2', - light ? 'min-w-96 max-h-svh overflow-y-auto' : '' - )} - > - <SchemaForm onlyMaskPassword bind:args={default_payload} {defaultValues} {schema} /> - </div> - <Tooltip> - The payload is optional, it is passed to the following step through the `resume` - variable - </Tooltip> - {/if} </ApprovalActions> {/key} </div> diff --git a/frontend/src/lib/components/FlowTimeline.svelte b/frontend/src/lib/components/FlowTimeline.svelte index fd44399e30..a1d7ca44eb 100644 --- a/frontend/src/lib/components/FlowTimeline.svelte +++ b/frontend/src/lib/components/FlowTimeline.svelte @@ -1,5 +1,6 @@ <script lang="ts"> import { displayDate, msToCompactDuration } from '$lib/utils' + import { ConcurrencyGroupsService } from '$lib/gen' import { Loader2 } from 'lucide-svelte' import TimelineBar from './TimelineBar.svelte' import WaitTimeWarning from './common/waitTimeWarning/WaitTimeWarning.svelte' @@ -135,6 +136,81 @@ }) const hasApprovalWait = $derived(Object.keys(approvalWaitByModule).length > 0) + + // The hold of a limited step's job once it started; a live hold comes from the step's state. + let holds = $state<Record<string, { from?: number; to?: number } | null>>({}) + $effect(() => { + for (const m of flowModules) { + if (!m.limited) continue + for (const j of items?.[m.id] ?? []) { + if (!j.started_at || j.id in untrack(() => holds)) continue + holds[j.id] = null + ConcurrencyGroupsService.getConcurrencyKeyStatus({ id: j.id }) + .then((s) => { + if (s?.deferred_from) + holds[j.id] = { + from: new Date(s.deferred_from).getTime(), + to: s.released_at ? new Date(s.released_at).getTime() : undefined + } + }) + .catch(() => {}) + } + } + }) + + type WaitSegment = { start: number; len: number; kind: 'sleep' | 'held' | 'wait' } + /** A job's wait split into the sleep before it, its concurrency hold and the rest. */ + function waitSegments( + m: FlowModuleForTimeline, + job: { id: string; created_at?: number; started_at?: number }, + single: boolean + ): WaitSegment[] { + const b = { ...job, created_at: job.created_at ?? now } + const end = b.started_at ?? now + const state = localModuleStates[m.id] + const live = b.started_at == undefined && state?.type === 'WaitingForExecutor' + let sleepEnd: number | undefined + if (single && live && state?.waiting_reason === 'sleep' && state.scheduled_for) + sleepEnd = new Date(state.scheduled_for).getTime() + else if (single && m.sleepBefore) sleepEnd = b.created_at + m.sleepBefore * 1000 + const hold = + live && state?.waiting_reason === 'concurrency' && state.held_since + ? { from: new Date(state.held_since).getTime(), to: undefined } + : holds[b.id] + const clamp = (t: number) => Math.min(Math.max(t, b.created_at), end) + const segments: WaitSegment[] = [] + let at = b.created_at + const push = (to: number, kind: WaitSegment['kind']) => { + to = clamp(to) + if (to > at) segments.push({ start: at, len: to - at, kind }) + at = Math.max(at, to) + } + if (sleepEnd != undefined) push(sleepEnd, 'sleep') + if (hold?.from != undefined) { + push(hold.from, 'wait') + push(hold.to ?? end, 'held') + } + push(end, 'wait') + return segments + } + const segmentStyle = { + // A wait like the gray one, striped as one the flow asked for. + sleep: { + colorClass: + 'bg-[repeating-linear-gradient(135deg,#d1d5db_0_4px,#e5e7eb_4px_8px)] dark:bg-[repeating-linear-gradient(135deg,#4b5563_0_4px,#374151_4px_8px)] !text-gray-700 dark:!text-gray-100', + label: 'Sleep' + }, + held: { colorClass: 'bg-orange-400/90', label: 'Held by concurrency limit' }, + wait: { colorClass: undefined, label: 'Wait' } + } + const hasSleep = $derived( + flowModules.some((m) => m.sleepBefore) || + Object.values(localModuleStates).some((s) => s.waiting_reason === 'sleep') + ) + const hasHold = $derived( + Object.values(holds).some((h) => h?.from != undefined) || + Object.values(localModuleStates).some((s) => s.waiting_reason === 'concurrency') + ) </script> <OnChange @@ -160,6 +236,20 @@ <div class="h-2.5 w-2.5 rounded-sm bg-blue-500/90"></div> <span>Execution</span> </div> + {#if hasSleep} + <div class="flex gap-1.5 items-center"> + <div + class="h-2.5 w-2.5 rounded-sm bg-[repeating-linear-gradient(135deg,#d1d5db_0_4px,#e5e7eb_4px_8px)] dark:bg-[repeating-linear-gradient(135deg,#4b5563_0_4px,#374151_4px_8px)]" + ></div> + <span>Sleep</span> + </div> + {/if} + {#if hasHold} + <div class="flex gap-1.5 items-center"> + <div class="h-2.5 w-2.5 rounded-sm bg-orange-400/90"></div> + <span>Concurrency limit</span> + </div> + {/if} {#if hasApprovalWait} <div class="flex gap-1.5 items-center"> <div class="h-2.5 w-2.5 rounded-sm bg-purple-400/80"></div> @@ -184,8 +274,11 @@ /> </div> {/if} - {#each flowModules as { id: k, type: typ, suspend: isSuspend, label } (k)} - {@const subItems = items?.[k]?.filter((x) => x.created_at && x.started_at)} + {#each flowModules as m (m.id)} + {@const { id: k, type: typ, suspend: isSuspend, label } = m} + {@const subItems = items?.[k]?.filter( + (x) => x.created_at && (x.started_at || localModuleStates[k]?.waiting_reason) + )} <div class="relative px-3 py-1.5"> <div class="flex items-center justify-between mb-0.5"> <div class="text-xs font-medium" @@ -238,20 +331,50 @@ : now - b?.created_at : 0} {@const aw = isSuspend ? approvalWaitByModule[k] : undefined} + {@const segments = + waitingLen < 100 ? [] : waitSegments(m, b, subItems?.length === 1)} <div class="flex w-full py-0.5 items-center" {style}> - <TimelineBar - position="left" - id={b?.id} - {total} - {min} - {compact} - gray - followedByBar={!!b.started_at} - spacerClass="bg-gray-100 dark:bg-gray-800/50 rounded-l-md" - started_at={b.created_at} - len={waitingLen < 100 ? 0 : waitingLen - 100} - running={b?.started_at == undefined} - /> + {#if segments.length <= 1} + <TimelineBar + position="left" + id={b?.id} + {total} + {min} + {compact} + gray + colorClass={segmentStyle[segments[0]?.kind ?? 'wait'].colorClass} + tooltip={segments[0] && segments[0].kind !== 'wait' + ? `${segmentStyle[segments[0].kind].label} · ${msToCompactDuration(segments[0].len, 1)}` + : undefined} + followedByBar={!!b.started_at} + spacerClass="bg-gray-100 dark:bg-gray-800/50 rounded-l-md" + started_at={b.created_at} + len={waitingLen < 100 ? 0 : waitingLen - 100} + running={b?.started_at == undefined} + /> + {:else} + {#each segments as seg, i (i)} + <TimelineBar + position={i === 0 ? 'left' : 'none'} + id={b?.id} + {total} + {min} + {compact} + gray + concat={i > 0} + colorClass={segmentStyle[seg.kind].colorClass} + tooltip="{segmentStyle[seg.kind].label} · {msToCompactDuration( + seg.len, + 1 + )}" + followedByBar + spacerClass="bg-gray-100 dark:bg-gray-800/50 rounded-l-md" + started_at={seg.start} + len={i === segments.length - 1 ? Math.max(seg.len - 100, 0) : seg.len} + running={b?.started_at == undefined} + /> + {/each} + {/if} {#if b.started_at} <TimelineBar position={aw || waitingLen < 100 ? 'center' : 'right'} diff --git a/frontend/src/lib/components/GitRepoViewer.svelte b/frontend/src/lib/components/GitRepoViewer.svelte index d00449f168..3de9cdedf0 100644 --- a/frontend/src/lib/components/GitRepoViewer.svelte +++ b/frontend/src/lib/components/GitRepoViewer.svelte @@ -325,7 +325,8 @@ loadFilePreviewRequest={HelpersService.loadGitRepoFilePreview} testConnectionRequest={(async (_d) => { const bucketConfig: any = await SettingService.getGlobal({ - key: 'object_store_cache_config' + key: 'object_store_cache_config', + dangerouslyRevealSecrets: true }) return SettingService.testObjectStorageConfig({ requestBody: bucketConfig diff --git a/frontend/src/lib/components/GlobalUserOffboardingModal.svelte b/frontend/src/lib/components/GlobalUserOffboardingModal.svelte index 38bbf7b191..aa739a2b64 100644 --- a/frontend/src/lib/components/GlobalUserOffboardingModal.svelte +++ b/frontend/src/lib/components/GlobalUserOffboardingModal.svelte @@ -4,11 +4,12 @@ import { apiErrorMessage, classNames } from '$lib/utils' import { AlertTriangle, CornerDownLeft, Loader2 } from 'lucide-svelte' import { UserService, FolderService } from '$lib/gen' - import type { WorkspaceOffboardPreview } from '$lib/gen' + import type { OffboardPathConflict, WorkspaceOffboardPreview } from '$lib/gen' import { sendUserToast } from '$lib/toast' import Toggle from '$lib/components/Toggle.svelte' import OffboardWorkspaceSection from './OffboardWorkspaceSection.svelte' - import { countPaths } from './offboarding-utils' + import OffboardConflictList from './OffboardConflictList.svelte' + import { countPaths, withoutConflict } from './offboarding-utils' type Props = { open: boolean @@ -25,7 +26,7 @@ let submitting = $state(false) let doReassign = $state(true) let deleteUser = $state(true) - let conflicts: string[] = $state([]) + let conflicts: OffboardPathConflict[] = $state([]) $effect(() => { deleteUser = !reassignOnly @@ -169,8 +170,8 @@ delete_user: deleteUser } }) - if (result.conflicts && result.conflicts.length > 0) { - conflicts = result.conflicts + if (result.conflict_items && result.conflict_items.length > 0) { + conflicts = result.conflict_items } else { sendUserToast( deleteUser @@ -315,17 +316,11 @@ {/if} {#if conflicts.length > 0} - <Alert type="error" title="Path conflicts detected"> - <p class="text-xs mb-1" - >These items already exist at the target. Rename or delete them, or choose a - different user/folder.</p - > - <ul class="text-xs list-disc list-inside max-h-32 overflow-y-auto"> - {#each conflicts as conflict, i (i)} - <li>{conflict}</li> - {/each} - </ul> - </Alert> + <OffboardConflictList + {conflicts} + showWorkspace + onResolved={(c) => (conflicts = withoutConflict(conflicts, c))} + /> {/if} </div> {/if} diff --git a/frontend/src/lib/components/InstanceNameEditor.svelte b/frontend/src/lib/components/InstanceNameEditor.svelte index 9d21da963c..6c7db11bf0 100644 --- a/frontend/src/lib/components/InstanceNameEditor.svelte +++ b/frontend/src/lib/components/InstanceNameEditor.svelte @@ -18,6 +18,9 @@ username?: string | undefined automateUsernameCreation?: boolean login_type: string + /** Whether the user has two-factor authentication; the section shows only then. */ + totpEnabled?: boolean + totpRequired?: boolean } let { @@ -25,7 +28,9 @@ email, username = undefined, automateUsernameCreation = false, - login_type = $bindable() + login_type = $bindable(), + totpEnabled = false, + totpRequired = false }: Props = $props() let password: string = $state('') @@ -44,6 +49,11 @@ sendUserToast(`Password updated for ${email}`) } + async function removeTotp() { + sendUserToast(await UserService.resetTotpOfUser({ user: email })) + dispatch('refresh') + } + async function saveLoginType() { await UserService.setLoginTypeForUser({ user: email, requestBody: { login_type } }) sendUserToast(`Login type updated for ${email}`) @@ -173,6 +183,25 @@ Update login type </Button> </label> + {#if totpEnabled} + <div class="block text-primary"> + <div class="pb-1 text-xs font-semibold text-emphasis">Two-factor authentication</div> + <div class="text-2xs text-secondary mb-1"> + For a user who lost their authenticator and recovery codes. {totpRequired + ? 'They set it up again at their next login.' + : 'They can set it up again from their user settings.'} + </div> + <Button + unifiedSize="md" + variant="default" + buttonType="button" + btnClasses="mt-2" + onclick={removeTotp} + > + Remove two-factor + </Button> + </div> + {/if} </div> {/snippet} </Popover> diff --git a/frontend/src/lib/components/InstanceSetting.svelte b/frontend/src/lib/components/InstanceSetting.svelte index 32c97f6623..dd526f0e8a 100644 --- a/frontend/src/lib/components/InstanceSetting.svelte +++ b/frontend/src/lib/components/InstanceSetting.svelte @@ -23,6 +23,8 @@ import RetentionPeriodOverrides from './instanceSettings/RetentionPeriodOverrides.svelte' import AgentWorkloadIdentityIssuers from './instanceSettings/AgentWorkloadIdentityIssuers.svelte' import McpExternalIdp from './instanceSettings/McpExternalIdp.svelte' + import InstanceIpAllowlist from './instanceSettings/InstanceIpAllowlist.svelte' + import OtelAuditLogsSettings from './instanceSettings/OtelAuditLogsSettings.svelte' import WorkspaceRolesSetting from './instanceSettings/WorkspaceRolesSetting.svelte' import SmtpSettings from './instanceSettings/SmtpSettings.svelte' import SecretBackendConfig from './instanceSettings/SecretBackendConfig.svelte' @@ -128,7 +130,8 @@ async function reloadLicenseKey() { $values['license_key'] = await SettingService.getGlobal({ - key: 'license_key' + key: 'license_key', + dangerouslyRevealSecrets: true }) } @@ -646,6 +649,8 @@ <AgentWorkloadIdentityIssuers {values} disabled={!$enterpriseLicense} /> {:else if setting.fieldType == 'mcp_external_idp'} <McpExternalIdp {values} disabled={!$enterpriseLicense} /> + {:else if setting.fieldType == 'instance_ip_allowlist'} + <InstanceIpAllowlist {values} licensed={!!$enterpriseLicense} /> {:else if setting.fieldType == 'critical_error_channels'} <CriticalAlertChannels {values} {openSmtpSettings} {oauths} /> {:else if setting.fieldType == 'otel'} @@ -724,6 +729,7 @@ Service name, environment, resource attributes, metrics temporality and other options are set with environment variables. </Description> + <OtelAuditLogsSettings {values} disabled={!$enterpriseLicense} /> {/if} </div> {:else if setting.fieldType == 'otel_tracing_proxy'} diff --git a/frontend/src/lib/components/InstanceSettings.svelte b/frontend/src/lib/components/InstanceSettings.svelte index 52919b19f9..4729648c3d 100644 --- a/frontend/src/lib/components/InstanceSettings.svelte +++ b/frontend/src/lib/components/InstanceSettings.svelte @@ -38,6 +38,7 @@ import WorkspaceRegistries from './instanceSettings/WorkspaceRegistries.svelte' import DbHealth from './instanceSettings/DbHealth.svelte' import OidcSigningStatus from './instanceSettings/OidcSigningStatus.svelte' + import ClientIpStatus from './instanceSettings/ClientIpStatus.svelte' interface Props { tab?: string @@ -135,7 +136,7 @@ loading = true // Bulk-load all settings in a single API call - const config = await SettingService.getInstanceConfig() + const config = await SettingService.getInstanceConfig({ dangerouslyRevealSecrets: true }) const gs = (config.global_settings ?? {}) as Record<string, any> initialOauths = gs['oauths'] ?? {} @@ -1165,6 +1166,13 @@ {#if $enterpriseLicense} <OidcSigningStatus /> {/if} + {:else if category == 'Client IP'} + <SettingsPageHeader + title="Client IP" + description="The address Windmill records as a request's client: in audit logs, for login rate limits and for token IP allowlists. Forwarding headers are believed only from the proxies trusted here. The TRUSTED_PROXIES, TRUST_CLOUDFLARE and CLIENT_IP_HEADER environment variables, when set, take precedence." + link="https://www.windmill.dev/docs/advanced/self_host#client-ip-behind-a-reverse-proxy" + /> + <ClientIpStatus {values} {loading} /> {:else if category == 'Agent workers'} <SettingsPageHeader title="Agent workers" @@ -1202,7 +1210,7 @@ <div class="flex-col flex gap-6 pb-6"> {#each settings[category] as setting} <!-- slack connect is handled with the alert channels settings, smtp_connect is handled in InstanceSetting --> - {#if setting.fieldType != 'slack_connect' && !(quickSetup && setting.hideInQuickSetup) && !(quickSetup && category === 'Core' && setting.key === 'license_key') && !(setting.key === 'mcp_external_idp' && authSubTab !== 'sso')} + {#if setting.fieldType != 'slack_connect' && setting.fieldType != 'client_ip' && !(quickSetup && setting.hideInQuickSetup) && !(quickSetup && category === 'Core' && setting.key === 'license_key') && !(setting.key === 'mcp_external_idp' && authSubTab !== 'sso')} <InstanceSetting {openSmtpSettings} on:closeDrawer={() => closeDrawer?.()} diff --git a/frontend/src/lib/components/JobStatus.svelte b/frontend/src/lib/components/JobStatus.svelte index a905f32874..06f4bde461 100644 --- a/frontend/src/lib/components/JobStatus.svelte +++ b/frontend/src/lib/components/JobStatus.svelte @@ -14,9 +14,13 @@ interface Props { job: QueuedJob | CompletedJob | undefined large?: boolean + /** Its concurrency limit has held the job back, so a later due time is the next check. */ + heldByConcurrency?: boolean + /** Why the step the flow is at has not started. */ + stepWaiting?: 'sleep' | 'concurrency' } - let { job, large = false }: Props = $props() + let { job, large = false, heldByConcurrency = false, stepWaiting }: Props = $props() let continuedOnError = $derived(job?.flow_status?.continued_on_error ?? []) </script> @@ -90,6 +94,12 @@ {/if} </Badge> </div> +{:else if job && 'running' in job && job.running && stepWaiting} + <div> + <Badge {large} color={stepWaiting === 'sleep' ? 'gray' : 'orange'}> + {stepWaiting === 'sleep' ? 'Sleeping' : 'Step held by concurrency limit'} + </Badge> + </div> {:else if job && 'running' in job && job.running} <div class="flex flex-row flex-wrap gap-1 items-center"> <Badge {large} color="yellow"> @@ -100,6 +110,12 @@ </Badge> {@render continuedOnErrorBadge()} </div> +{:else if job && 'running' in job && heldByConcurrency} + <div> + <Badge color="orange" {large} title="Next check by {displayDate(job.scheduled_for, true)}"> + Held by concurrency limit + </Badge> + </div> {:else if job && 'running' in job && 'scheduled_for' in job && job.scheduled_for && forLater(job.scheduled_for)} <div> <Badge color="blue" {large}> diff --git a/frontend/src/lib/components/Login.svelte b/frontend/src/lib/components/Login.svelte index d76136c728..45e7199df6 100644 --- a/frontend/src/lib/components/Login.svelte +++ b/frontend/src/lib/components/Login.svelte @@ -40,9 +40,20 @@ import Password from './Password.svelte' import TextInput from './text_input/TextInput.svelte' import { sameTopDomainOrigin } from '$lib/cookies' - import { isValidLogoutRedirect, toSameOriginRelativePath } from '$lib/logoutRedirect' + import { + isValidLogoutRedirect, + toRedirectTarget, + toSameOriginRelativePath + } from '$lib/logoutRedirect' import InputError from './InputError.svelte' - import { loginErrorMessage } from '$lib/loginError' + import { + loginErrorDetail, + loginErrorMessage, + TOTP_INVALID_MESSAGE, + TOTP_REQUIRED, + TOTP_SETUP_REQUIRED + } from '$lib/loginError' + import { parseAccountSettingsHash } from './sidebar/settings' import Badge from './common/badge/Badge.svelte' import { getLastLoginMethod, @@ -78,6 +89,9 @@ * same sign-in without this, which provisions them for real. Password login * ignores it: a guest has no stored credential to check. */ guestApp?: string | undefined + /** Once a password login succeeds, offer to set up two-factor authentication before + * leaving the card, for an account that has none. The user can skip it. */ + offerTotpSetup?: boolean } let { @@ -92,7 +106,8 @@ onLoginError = undefined, preview = undefined, onOptionsLoaded = undefined, - guestApp = undefined + guestApp = undefined, + offerTotpSetup = false }: Props = $props() // The harness never takes effect in a production bundle, whatever a caller passes. @@ -108,6 +123,7 @@ const emailId = `${uid}-email` const passwordId = `${uid}-password` const errorId = `${uid}-error` + const totpId = `${uid}-totp` const emailErrorId = `${uid}-email-error` const providers = [ @@ -182,6 +198,43 @@ let showPassword = $state(false) let passwordField = $state<Password | undefined>(undefined) + // The account the server asked an authenticator code for, or asked to set up two-factor + // authentication when the instance requires it. These steps replace the form and resend the + // password kept here, so the server needs no half-logged-in state. + let totpFor = $state<string | undefined>(undefined) + let totpCode = $state('') + let totpField = $state<TextInput | undefined>(undefined) + let showTotp = $derived(totpFor !== undefined && totpFor === email) + let enrollSetup = $state<{ secret: string; otpauth_url: string } | undefined>(undefined) + // Kept across Back: asking the server again replaces the pending secret, and the QR code the + // user already scanned would stop working. + let issuedSetup: { email: string; setup: { secret: string; otpauth_url: string } } | undefined + let enrollCodes = $state<string[] | undefined>(undefined) + // The setup was offered after a successful login, rather than required before one: a + // session exists, so it goes through the signed-in routes and can be skipped. + let enrollOptional = $state(false) + let enrollSaved = $state(false) + + async function openTotpStep(forEmail: string, setup?: { secret: string; otpauth_url: string }) { + formError = undefined + shake = false + totpFor = forEmail + totpCode = '' + enrollSetup = setup + await tick() + totpField?.focus() + } + + async function leaveTotp() { + totpFor = undefined + totpCode = '' + enrollSetup = undefined + formError = undefined + // The swapped-in markup would otherwise replay a shake left on from a failed attempt. + shake = false + await tick() + passwordField?.focus() + } // Type argument rather than annotation: annotating narrows the declaration to the // initializer's `undefined`, so a top-level read sees `never` instead of the array. let logins = $state<OAuthLogin[] | undefined>(undefined) @@ -199,7 +252,7 @@ let formError = $state< | { message: string - fields: 'both' | 'email' | 'password' + fields: 'both' | 'email' | 'password' | 'totp' email: string | undefined password: string | undefined } @@ -220,7 +273,7 @@ async function failLogin( message: string, - fields: 'both' | 'email' | 'password' = 'both', + fields: 'both' | 'email' | 'password' | 'totp' = 'both', // The pair the message is about. Defaults to what is in the fields right now, but a // rejected request passes what it actually submitted: the user may have typed on since. attempted: { email: string | undefined; password: string | undefined } = { email, password } @@ -244,7 +297,20 @@ displayName: string } + // One submit at a time: a second setup request would replace the pending secret, and the + // page could then show a QR code the server no longer accepts. + let submitting = false async function login(): Promise<void> { + if (submitting) return + submitting = true + try { + await submitLogin() + } finally { + submitting = false + } + } + + async function submitLogin(): Promise<void> { if (!email || !password) { if (!email && !password) failLogin('Enter both your email and password.') else if (!email) failLogin('Enter your email.', 'email') @@ -257,9 +323,20 @@ return } + if (showTotp && !totpCode.trim()) { + failLogin('Enter the code from your authenticator app.', 'totp') + return + } + + if (showTotp && enrollSetup) { + await enableTotpAtLogin() + return + } + const requestBody = { email, - password + password, + totp_code: showTotp ? totpCode : undefined } // Await the DOM update: the field must be back to type="password" before the @@ -273,10 +350,66 @@ // previous account must not be served to this one. noteSessionEmail(email) } catch (err) { - failLogin(loginErrorMessage(err), 'both', requestBody) + const detail = loginErrorDetail(err) + if (detail === TOTP_REQUIRED) { + await openTotpStep(requestBody.email) + return + } + if (detail === TOTP_SETUP_REQUIRED) { + try { + const setup = + issuedSetup?.email === requestBody.email + ? issuedSetup.setup + : await UserService.loginTotpSetup({ + requestBody: { email: requestBody.email, password: requestBody.password } + }) + issuedSetup = { email: requestBody.email, setup } + await openTotpStep(requestBody.email, setup) + } catch (setupErr) { + failLogin(loginErrorMessage(setupErr), 'both', requestBody) + } + return + } + const message = loginErrorMessage(err) + failLogin(message, message === TOTP_INVALID_MESSAGE ? 'totp' : 'both', requestBody) return } + if (offerTotpSetup && !requestBody.totp_code) { + // Refused when the account already has a second factor, or by a build or edition + // that cannot give it one: the login then simply goes on. + const setup = await UserService.setupTotp({ + requestBody: { password: requestBody.password } + }).catch(() => undefined) + if (setup) { + enrollOptional = true + await openTotpStep(requestBody.email, setup) + return + } + } + + await finishLogin() + } + + // Turns the second factor on and, when it was required, starts the session in the same + // request; the recovery codes it returns are shown before leaving the page. + async function enableTotpAtLogin(): Promise<void> { + const requestBody = { email: email!, password: password!, code: totpCode } + try { + const { recovery_codes } = enrollOptional + ? await UserService.enableTotp({ requestBody: { code: totpCode } }) + : await UserService.loginTotpEnable({ requestBody }) + noteSessionEmail(requestBody.email) + formError = undefined + enrollSetup = undefined + enrollCodes = recovery_codes + } catch (err) { + const message = loginErrorMessage(err) + failLogin(message, message === TOTP_INVALID_MESSAGE ? 'totp' : 'both', requestBody) + } + } + + async function finishLogin(): Promise<void> { formError = undefined rememberLoginMethod({ kind: 'password' }) @@ -305,8 +438,9 @@ async function redirectUser() { // Reduce same-origin full URLs to relative paths so deep links from // e.g. /a/[...path] (which carry the full URL as rd) still navigate - // correctly instead of falling through to the cross-origin branch. - let resolvedRd = toSameOriginRelativePath(rd) ?? rd + // correctly instead of falling through to the cross-origin branch. A value that is + // not a valid target is dropped rather than handed to `goto`. + let resolvedRd = toRedirectTarget(rd) ?? undefined if (resolvedRd?.startsWith('http')) { if (isValidLogoutRedirect(resolvedRd)) { window.location.href = resolvedRd @@ -357,8 +491,8 @@ resolvedRd?.startsWith('/projects/import') ) { goto(resolvedRd) - } else if (resolvedRd == '/#user-settings') { - goto(`/user/workspaces#user-settings`) + } else if (resolvedRd?.startsWith('/#') && parseAccountSettingsHash(resolvedRd.slice(1))) { + goto(`/user/workspaces${resolvedRd.slice(1)}`) } else { goto(`/user/workspaces${resolvedRd ? `?rd=${encodeURIComponent(resolvedRd)}` : ''}`) } @@ -759,130 +893,219 @@ <p class="text-sm text-center text-secondary py-4">Signing you in…</p> {/if} - {#if !passwordFirst} - {@render providerButtons()} - {#if !autoRedirecting && !disablePasswordLogin && (saml || (logins && logins.length > 0))} - {@render orDivider()} - <!-- Only an entry point to the form below: once that is open the divider is what - separates the two ways in. --> - {#if !showPassword} - <div class="center-center"> - <Button - unifiedSize="sm" - variant="subtle" - onClick={() => { - showPassword = true - }} - > - Log in without third-party - </Button> - </div> - {/if} - {/if} - {/if} - - {#if !autoRedirecting && showPassword && !disablePasswordLogin} - <div> - {#if firstTime} - <p class="text-xs text-center w-full pb-4 text-secondary"> - Welcome! Default credentials admin@windmill.dev / changeme have been prefilled. + {#if enrollCodes} + <div class="space-y-4"> + <div class="space-y-1"> + <h2 class="text-sm font-semibold text-emphasis">Two-factor authentication is on</h2> + <p class="text-xs text-secondary"> + Logging in with your password now also asks for a code from your authenticator app. </p> - {/if} - <div class="space-y-4"> - {#if cloudHosted} - <p class="text-xs text-secondary pb-6"> - To get credentials without the OAuth providers above, send an email at - contact@windmill.dev + </div> + <!-- Loaded on demand: the login page every visitor gets stays free of the QR encoder + and the code highlighter, which only these screens use. --> + {#await import('./settings/TotpRecoveryCodes.svelte') then { default: TotpRecoveryCodes }} + <TotpRecoveryCodes codes={enrollCodes} bind:saved={enrollSaved} /> + {/await} + <Button onClick={finishLogin} variant="accent" unifiedSize="lg" disabled={!enrollSaved}> + Continue + </Button> + </div> + {:else if showTotp} + <div class="space-y-4"> + <div class="space-y-1"> + {#if enrollSetup && enrollOptional} + <h2 class="text-sm font-semibold text-emphasis">Set up two-factor authentication</h2> + <p class="text-xs text-secondary"> + Protect {email} with a code from an authenticator app on top of its password. You can also + do this later from your user settings. + </p> + {:else if enrollSetup} + <h2 class="text-sm font-semibold text-emphasis">Set up two-factor authentication</h2> + <p class="text-xs text-secondary"> + This instance asks for a code from an authenticator app at each password login. Add + {email} to your app to continue. + </p> + {:else} + <h2 class="text-sm font-semibold text-emphasis">Two-factor authentication</h2> + <p class="text-xs text-secondary"> + Enter the code from your authenticator app for {email}, or one of your recovery codes. </p> {/if} - <div bind:this={fieldsEl} class="space-y-2 {shake ? 'motion-safe:animate-shake' : ''}"> - <div class="space-y-1"> - <label for={emailId} class="block text-xs font-semibold text-emphasis"> Email </label> - <div> - <TextInput - size="md" - error={emailErrored} - bind:value={email} - inputProps={{ - id: emailId, - type: 'email', - autocomplete: 'username', - 'aria-invalid': emailErrored ? 'true' : undefined, - 'aria-describedby': - errorField === 'email' ? emailErrorId : emailErrored ? errorId : undefined, - onkeydown: (e) => { - // Only move on once the field holds something: while the browser's - // credential dropdown is open, Enter belongs to the dropdown - if (e.key === 'Enter' && !e.isComposing && !e.repeat && e.currentTarget.value) { - e.preventDefault() - passwordField?.focus() - } - } - }} - /> - </div> - <div id={emailErrorId} role="alert" class="min-h-5"> - {#if errorField === 'email'} - <InputError error={credentialsError} /> - {/if} - </div> - </div> - - <div class="space-y-1"> - <label for={passwordId} class="block text-xs font-semibold text-emphasis"> - Password - </label> - <div> - <Password - bind:this={passwordField} - bind:password - id={passwordId} - placeholder="" - autocomplete="current-password" - allowMultiline={false} - error={passwordErrored} - describedBy={passwordErrored ? errorId : undefined} - onKeyDown={handleKeyDown} - /> - </div> - {@render errorMessage()} - </div> - </div> - - <div> - <Button onClick={login} variant="accent" unifiedSize="lg" disabled={!email || !password}> - Log in - </Button> - {#if smtpConfigured} - <div class="text-center pt-2"> - <a - href="/user/forgot-password" - class="text-2xs text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300" - > - Forgot password? - </a> - </div> + </div> + {#if enrollSetup} + {#await import('./settings/TotpAuthenticator.svelte') then { default: TotpAuthenticator }} + <TotpAuthenticator setup={enrollSetup} /> + {/await} + {/if} + <div bind:this={fieldsEl} class="space-y-1 {shake ? 'motion-safe:animate-shake' : ''}"> + <label for={totpId} class="block text-xs font-semibold text-emphasis"> + {enrollSetup ? 'The 6-digit code your app shows' : 'Authentication code'} + </label> + <TextInput + bind:this={totpField} + size="md" + bind:value={totpCode} + error={!!errorField} + inputProps={{ + id: totpId, + name: 'totp', + 'aria-invalid': errorField ? 'true' : undefined, + 'aria-describedby': errorField ? errorId : undefined, + autocomplete: 'one-time-code', + onkeydown: handleKeyDown + }} + /> + {@render errorMessage()} + </div> + <div class="space-y-2"> + <Button onClick={login} variant="accent" unifiedSize="lg" disabled={!totpCode.trim()}> + {enrollOptional ? 'Turn on' : enrollSetup ? 'Turn on and log in' : 'Verify'} + </Button> + <div class="center-center"> + {#if enrollOptional} + <Button unifiedSize="sm" variant="subtle" onClick={finishLogin}>Skip for now</Button> + {:else} + <Button unifiedSize="sm" variant="subtle" onClick={leaveTotp}>Back</Button> {/if} </div> </div> - - {#if cloudHosted} - <p class="text-2xs text-secondary mt-10 text-center"> - By logging in, you agree to our - <a href="https://windmill.dev/terms_of_service" target="_blank" rel="noreferrer"> - Terms of service - </a> - and - <a href="https://windmill.dev/privacy_policy" target="_blank" rel="noreferrer"> - Privacy policy - </a> - </p> - {/if} </div> - {/if} + {:else} + {#if !passwordFirst} + {@render providerButtons()} + {#if !autoRedirecting && !disablePasswordLogin && (saml || (logins && logins.length > 0))} + {@render orDivider()} + <!-- Only an entry point to the form below: once that is open the divider is what + separates the two ways in. --> + {#if !showPassword} + <div class="center-center"> + <Button + unifiedSize="sm" + variant="subtle" + onClick={() => { + showPassword = true + }} + > + Log in without third-party + </Button> + </div> + {/if} + {/if} + {/if} - {#if passwordFirst && (saml || (logins && logins.length > 0))} - {@render orDivider()} - {@render providerButtons()} + {#if !autoRedirecting && showPassword && !disablePasswordLogin} + <div> + {#if firstTime} + <p class="text-xs text-center w-full pb-4 text-secondary"> + Welcome! Default credentials admin@windmill.dev / changeme have been prefilled. + </p> + {/if} + <div class="space-y-4"> + {#if cloudHosted} + <p class="text-xs text-secondary pb-6"> + To get credentials without the OAuth providers above, send an email at + contact@windmill.dev + </p> + {/if} + <div bind:this={fieldsEl} class="space-y-2 {shake ? 'motion-safe:animate-shake' : ''}"> + <div class="space-y-1"> + <label for={emailId} class="block text-xs font-semibold text-emphasis"> Email </label> + <div> + <TextInput + size="md" + error={emailErrored} + bind:value={email} + inputProps={{ + id: emailId, + type: 'email', + autocomplete: 'username', + 'aria-invalid': emailErrored ? 'true' : undefined, + 'aria-describedby': + errorField === 'email' ? emailErrorId : emailErrored ? errorId : undefined, + onkeydown: (e) => { + // Only move on once the field holds something: while the browser's + // credential dropdown is open, Enter belongs to the dropdown + if ( + e.key === 'Enter' && + !e.isComposing && + !e.repeat && + e.currentTarget.value + ) { + e.preventDefault() + passwordField?.focus() + } + } + }} + /> + </div> + <div id={emailErrorId} role="alert" class="min-h-5"> + {#if errorField === 'email'} + <InputError error={credentialsError} /> + {/if} + </div> + </div> + + <div class="space-y-1"> + <label for={passwordId} class="block text-xs font-semibold text-emphasis"> + Password + </label> + <div> + <Password + bind:this={passwordField} + bind:password + id={passwordId} + placeholder="" + autocomplete="current-password" + allowMultiline={false} + error={passwordErrored} + describedBy={passwordErrored ? errorId : undefined} + onKeyDown={handleKeyDown} + /> + </div> + {@render errorMessage()} + </div> + </div> + + <div> + <Button + onClick={login} + variant="accent" + unifiedSize="lg" + disabled={!email || !password} + > + Log in + </Button> + {#if smtpConfigured} + <div class="text-center pt-2"> + <a + href="/user/forgot-password" + class="text-2xs text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300" + > + Forgot password? + </a> + </div> + {/if} + </div> + </div> + + {#if cloudHosted} + <p class="text-2xs text-secondary mt-10 text-center"> + By logging in, you agree to our + <a href="https://windmill.dev/terms_of_service" target="_blank" rel="noreferrer"> + Terms of service + </a> + and + <a href="https://windmill.dev/privacy_policy" target="_blank" rel="noreferrer"> + Privacy policy + </a> + </p> + {/if} + </div> + {/if} + + {#if passwordFirst && (saml || (logins && logins.length > 0))} + {@render orDivider()} + {@render providerButtons()} + {/if} {/if} </div> diff --git a/frontend/src/lib/components/ModuleStatus.svelte b/frontend/src/lib/components/ModuleStatus.svelte index 351b3e0d03..3615d8d29f 100644 --- a/frontend/src/lib/components/ModuleStatus.svelte +++ b/frontend/src/lib/components/ModuleStatus.svelte @@ -1,32 +1,73 @@ <script lang="ts"> import type { FlowStatusModule } from '$lib/gen' + import type { GraphModuleState } from './graph' import { Badge } from './common' import { forLater } from '$lib/forLater' - import { displayDate } from '$lib/utils' - import { Hourglass } from 'lucide-svelte' + import { displayDate, msToCompactDuration } from '$lib/utils' + import { Gauge, Hourglass, Moon } from 'lucide-svelte' + import { useApprovalCount } from './graph/approvalCount.svelte' interface Props { - type: FlowStatusModule['type']; - scheduled_for: Date | undefined; - skipped?: boolean; + type: FlowStatusModule['type'] + scheduled_for: Date | undefined + waiting_reason?: GraphModuleState['waiting_reason'] + concurrency_key?: string + /** When its concurrency limit first held the step back. */ + held_since?: string + approval_wait?: GraphModuleState['approval_wait'] + skipped?: boolean } - let { type, scheduled_for, skipped = false }: Props = $props(); + let { + type, + scheduled_for, + waiting_reason = undefined, + concurrency_key = undefined, + held_since = undefined, + approval_wait = undefined, + skipped = false + }: Props = $props() + + const approval = useApprovalCount(() => approval_wait) + + let now = $state(Date.now()) + $effect(() => { + if (!waiting_reason) return + const id = setInterval(() => (now = Date.now()), 1000) + return () => clearInterval(id) + }) + let sleepLeft = $derived(Math.max(new Date(scheduled_for ?? now).getTime() - now, 0)) + let heldFor = $derived(held_since ? Math.max(now - new Date(held_since).getTime(), 0) : undefined) </script> {#if type == 'WaitingForEvents'} - <span class="italic text-xs text-violet-700 dark:text-violet-400"> - <Hourglass class="inline" size={14} /> - Waiting to be resumed by resume events such as approvals + <span class="italic text-xs text-primary"> + <Hourglass class="inline text-violet-500" size={14} /> + {approval_wait ? approval.label : 'Waiting to be resumed by resume events such as approvals'} </span> {:else if type == 'WaitingForPriorSteps'} <span class="italic text-xs text-primary"> <Hourglass class="inline" size={14} /> Waiting for prior steps to complete </span> +{:else if type == 'WaitingForExecutor' && waiting_reason === 'sleep'} + <span class="italic text-xs text-primary"> + <Moon class="inline" size={14} /> + Sleeping until {displayDate(scheduled_for, true)} · {msToCompactDuration(sleepLeft, 0)} left + </span> +{:else if type == 'WaitingForExecutor' && waiting_reason === 'concurrency'} + <span class="italic text-xs text-primary"> + <Gauge class="inline text-orange-500" size={14} /> + Held by concurrency limit{heldFor != undefined + ? ` · ${msToCompactDuration(heldFor, 0)}` + : ''}{concurrency_key ? ` (key ${concurrency_key})` : ''}, next check by {displayDate( + scheduled_for, + true + )} + </span> {:else if type == 'WaitingForExecutor'} <span class="italic text-xs text-primary"> - <Hourglass class="inline" /> + <Hourglass class="inline" size={14} /> {#if scheduled_for && forLater(scheduled_for.toString())} Job is scheduled to be executed at {displayDate(scheduled_for, true)} {:else} diff --git a/frontend/src/lib/components/NextcloudSetting.svelte b/frontend/src/lib/components/NextcloudSetting.svelte index 924ad03e8e..2b81f09980 100644 --- a/frontend/src/lib/components/NextcloudSetting.svelte +++ b/frontend/src/lib/components/NextcloudSetting.svelte @@ -98,25 +98,6 @@ bind:password={value['secret']} /> </label> - <div> - <Toggle - options={{ - right: - 'Allow workspace admins to set up Nextcloud integration triggers using these credentials' - }} - checked={value['share_with_workspaces'] ?? false} - on:change={(e) => { - value = { ...value, share_with_workspaces: e.detail } - }} - /> - {#if value['share_with_workspaces']} - <p class="text-xs text-tertiary mt-1"> - Workspace admins will be able to connect Nextcloud integration triggers without - configuring their own OAuth client. The credentials are not exposed to them. Connections - use whichever redirect URI the client is registered with. - </p> - {/if} - </div> <CollapseLink text="Instructions"> <div class="text-xs text-primary border rounded-md p-4"> 1. Go to your Nextcloud instance as an administrator<br /> diff --git a/frontend/src/lib/components/OffboardConflictList.svelte b/frontend/src/lib/components/OffboardConflictList.svelte new file mode 100644 index 0000000000..92d3dd7632 --- /dev/null +++ b/frontend/src/lib/components/OffboardConflictList.svelte @@ -0,0 +1,133 @@ +<script lang="ts"> + import { Alert, Button } from '$lib/components/common' + import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte' + import type { OffboardPathConflict } from '$lib/gen' + import { apiErrorMessage } from '$lib/utils' + import { sendUserToast } from '$lib/toast' + import { + canDeleteKind, + conflictsGoneAfterDelete, + deleteItemOfKind, + isTrashedKind, + itemHref, + kindLabel + } from './offboarding-utils' + + type Props = { + conflicts: OffboardPathConflict[] + /** Prefix each line with its workspace (instance-level offboarding). */ + showWorkspace?: boolean + onResolved: (conflict: OffboardPathConflict) => void + } + + let { conflicts, showWorkspace = false, onResolved }: Props = $props() + + type Action = 'overwrite' | 'discard' + let pending: { conflict: OffboardPathConflict; action: Action } | undefined = $state(undefined) + let deleting = $state(false) + + function pathToDelete(p: NonNullable<typeof pending>): string { + return p.action === 'overwrite' ? p.conflict.target_path : p.conflict.source_path + } + + async function confirm() { + if (!pending) return + const { conflict } = pending + const path = pathToDelete(pending) + deleting = true + try { + await deleteItemOfKind(conflict.kind, conflict.workspace_id, path) + } catch (e) { + sendUserToast(`Could not delete ${path}: ${apiErrorMessage(e)}`, true) + deleting = false + return + } + sendUserToast(`Deleted ${kindLabel(conflict.kind)} ${path}`) + const remaining = conflicts.filter((c) => c !== conflict) + onResolved(conflict) + pending = undefined + try { + for (const gone of await conflictsGoneAfterDelete(conflict.kind, remaining)) { + onResolved(gone) + } + } catch (e) { + sendUserToast(`Could not refresh the remaining conflicts: ${apiErrorMessage(e)}`, true) + } finally { + deleting = false + } + } +</script> + +<Alert type="error" title="Path conflicts detected"> + <p class="text-xs mb-2"> + These items already exist at the target. For each one, overwrite the existing item with the + reassigned one, or discard the reassigned one and keep the existing item. You can also choose a + different user/folder. + </p> + <ul class="flex flex-col gap-1 max-h-48 overflow-y-auto"> + {#each conflicts as conflict (`${conflict.workspace_id}:${conflict.kind}:${conflict.source_path}`)} + {@const href = itemHref(conflict.kind, conflict.target_path)} + <li class="flex items-center gap-2 text-xs"> + <span class="flex-1 min-w-0 truncate" title={conflict.target_path}> + {#if showWorkspace} + <span class="text-secondary">[{conflict.workspace_id}]</span> + {/if} + <span class="text-secondary">{kindLabel(conflict.kind)}:</span> + {#if href && !showWorkspace} + <a {href} target="_blank" rel="noopener noreferrer">{conflict.target_path}</a> + {:else} + {conflict.target_path} + {/if} + </span> + {#if canDeleteKind(conflict.kind)} + <Button + unifiedSize="xs" + variant="default" + disabled={deleting} + destructive + title="Delete the existing {conflict.target_path} so {conflict.source_path} can take its place" + onclick={() => (pending = { conflict, action: 'overwrite' })} + > + Overwrite target + </Button> + <Button + unifiedSize="xs" + variant="default" + disabled={deleting} + title="Delete {conflict.source_path} and keep the existing {conflict.target_path}" + onclick={() => (pending = { conflict, action: 'discard' })} + > + Discard + </Button> + {/if} + </li> + {/each} + </ul> +</Alert> + +<ConfirmationModal + open={pending != undefined} + title={pending?.action === 'overwrite' ? 'Overwrite target' : 'Discard reassigned item'} + confirmationText="Delete" + loading={deleting} + trashbin={pending != undefined && isTrashedKind(pending.conflict.kind)} + zIndexClass="z-[6000]" + alwaysPortal + onConfirmed={confirm} + onCanceled={() => (pending = undefined)} +> + {#if pending} + <p class="text-sm"> + {#if pending.action === 'overwrite'} + The existing {kindLabel(pending.conflict.kind)} + <span class="font-mono">{pending.conflict.target_path}</span> will be deleted, and + <span class="font-mono">{pending.conflict.source_path}</span> will be moved to that path on reassignment. + {:else} + The {kindLabel(pending.conflict.kind)} + <span class="font-mono">{pending.conflict.source_path}</span> will be deleted instead of + being reassigned. The existing + <span class="font-mono">{pending.conflict.target_path}</span> is kept. + {/if} + </p> + {/if} +</ConfirmationModal> diff --git a/frontend/src/lib/components/OnBehalfOfSelector.svelte b/frontend/src/lib/components/OnBehalfOfSelector.svelte index 3c903ad424..bc7c40ed2b 100644 --- a/frontend/src/lib/components/OnBehalfOfSelector.svelte +++ b/frontend/src/lib/components/OnBehalfOfSelector.svelte @@ -1,5 +1,5 @@ <script lang="ts" module> - import { isTriggerOrScheduleKind } from 'windmill-utils-internal' + import { isTriggerOrScheduleKind } from 'windmill-utils-internal/deploy' export type OnBehalfOfChoice = 'target' | 'me' | 'custom' | undefined diff --git a/frontend/src/lib/components/ParqetCsvTableRenderer.svelte b/frontend/src/lib/components/ParqetCsvTableRenderer.svelte deleted file mode 100644 index da409b697a..0000000000 --- a/frontend/src/lib/components/ParqetCsvTableRenderer.svelte +++ /dev/null @@ -1,296 +0,0 @@ -<script lang="ts"> - import { run } from 'svelte/legacy' - - import { type GridApi, createGrid, type IDatasource } from 'ag-grid-community' - - import 'ag-grid-community/styles/ag-grid.css' - import 'ag-grid-community/styles/ag-theme-alpine.css' - import { twMerge } from 'tailwind-merge' - import DarkModeObserver from './DarkModeObserver.svelte' - import { AppService, HelpersService } from '$lib/gen' - import { downloadViaClient, shouldDownloadViaClient } from '$lib/utils/downloadFile' - import { enterpriseLicense } from '$lib/stores' - import { Download } from 'lucide-svelte' - import { Loader2 } from 'lucide-svelte' - import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' - - const operatingWorkspace = useOperatingWorkspace() - - // import 'ag-grid-community/dist/styles/ag-theme-alpine-dark.css' - - let selectedRowIndex = -1 - interface Props { - s3resource: string - storage: string | undefined - workspaceId: string | undefined - disable_download?: boolean - // When set (deployed app view), read the file on-behalf of the app author - // through the app-scoped, provenance-gated `apps_u/*` endpoints instead of - // the viewer-scoped `job_helpers/*` API. Undefined in the editor/preview. - appPath?: string | undefined - // HMAC bearer (`exp=..&sig=..`) minted by `signS3Objects`. When present on a - // deployed-app read, it bypasses the provenance gate — matching the download - // and image routes. Forwarded to every app-scoped preview/count/export call. - presigned?: string | undefined - } - - let { - s3resource, - storage, - workspaceId, - disable_download = false, - appPath = undefined, - presigned = undefined - }: Props = $props() - - // Split the presigned bearer into typed query params for the generated client. - // Only meaningful in deployed-app (`appPath`) reads; empty otherwise. - function presignedParams(): { sig?: string; exp?: string } { - if (!appPath || !presigned) return {} - const p = new URLSearchParams(presigned) - return { sig: p.get('sig') ?? undefined, exp: p.get('exp') ?? undefined } - } - - // Route the parquet/csv read through the app-scoped endpoints when `appPath` - // is set, else the viewer-scoped helpers. Same request/response shape either - // way — the only difference is which identity authorizes the S3 read. - function loadRowCount(searchCol: string | undefined, searchTerm: string | undefined) { - const workspace = workspaceId ?? $operatingWorkspace! - return appPath - ? AppService.appLoadTableCount({ - workspace, - path: appPath, - fileKey: s3resource, - searchCol, - searchTerm, - storage, - ...presignedParams() - }) - : HelpersService.loadTableRowCount({ - workspace, - path: s3resource, - searchCol, - searchTerm, - storage - }) - } - - function loadChunk(args: { - offset?: number - limit?: number - sortCol?: string - sortDesc?: boolean - searchCol?: string - searchTerm?: string - csvSeparator?: string - }) { - const workspace = workspaceId ?? $operatingWorkspace! - const csv = s3resource.endsWith('.csv') - if (appPath) { - const data = { - workspace, - path: appPath, - fileKey: s3resource, - storage, - ...args, - ...presignedParams() - } - return csv ? AppService.appLoadCsvPreview(data) : AppService.appLoadParquetPreview(data) - } - const data = { workspace, path: s3resource, storage, ...args } - return csv ? HelpersService.loadCsvPreview(data) : HelpersService.loadParquetPreview(data) - } - - let lastSearch: string | undefined = undefined - - let nbRows: number | undefined = $state(undefined) - let csvSeparatorChar: string = $state(',') - let datasource: IDatasource = { - rowCount: 0, - getRows: async function (params) { - try { - const searchCol = params.filterModel ? Object.keys(params.filterModel)?.[0] : undefined - const searchTerm = searchCol ? params.filterModel?.[searchCol]?.filter : undefined - const csv = s3resource.endsWith('.csv') - const newSearch = searchCol ? searchCol + searchTerm : undefined - if (!nbRows || lastSearch != newSearch) { - nbRows = undefined - const res = await loadRowCount(searchCol, searchTerm) - nbRows = res.count - lastSearch = newSearch - } - - const res = (await loadChunk({ - offset: params.startRow, - limit: params.endRow - params.startRow, - sortCol: params.sortModel?.[0]?.colId, - sortDesc: params.sortModel?.[0]?.sort == 'desc', - searchCol, - searchTerm, - csvSeparator: csv ? csvSeparatorChar : undefined - })) as any - for (let i = 0; i < res.rows.length; i++) { - res.rows[i]['__index'] = i + params.startRow - if (!$enterpriseLicense) { - Object.keys(res.rows[i]).forEach((key) => { - if (key != '__index') { - res.rows[i][key] = 'Require EE' - } - }) - } - } - - params.successCallback(res.rows, nbRows) - } catch (e) { - console.error(e) - params.failCallback() - } - } - } - - function toggleRow(row: any) { - if (row) { - let rowIndex = row.rowIndex - let data = { ...row.data } - delete data['__index'] - if (selectedRowIndex !== rowIndex) { - selectedRowIndex = rowIndex - } - } - } - - function toggleRows(rows: any[]) { - toggleRow(rows[0]) - } - - let eGui: HTMLDivElement | undefined = $state() - - let error: string | undefined = $state(undefined) - async function mountGrid() { - if (eGui) { - try { - const csv = s3resource.endsWith('.csv') - - const res = (await loadChunk({ - limit: 0, - csvSeparator: csv ? csvSeparatorChar : undefined - })) as any - - createGrid( - eGui, - { - rowModelType: 'infinite', - datasource, - // @ts-ignore - columnDefs: res.columns.map((c) => { - return { - field: c, - sortable: true, - filter: true, - filterParams: { - filterOptions: ['contains'], - maxNumConditions: 1 - } - } - }), - pagination: false, - // defaultColDef: { - // flex: 1 - // }, - suppressColumnMoveAnimation: true, - rowSelection: 'multiple', - rowMultiSelectWithClick: true, - suppressRowDeselection: true, - - onSelectionChanged: (e) => { - onSelectionChanged(e.api) - }, - getRowId: (data) => { - return (data as any).data['__index'] - } - }, - {} - ) - error = undefined - } catch (e) { - error = e.body - console.error(e) - } - } - } - - function onSelectionChanged(api: GridApi<any>) { - const rows = api.getSelectedNodes() - if (rows != undefined) { - toggleRows(rows) - } - } - - let darkMode: boolean = $state(false) - run(() => { - eGui && mountGrid() - }) -</script> - -<DarkModeObserver bind:darkMode /> - -<div class={twMerge('mt-2 flex flex-col h-full min-h-[600px]')}> - {#if s3resource.endsWith('.csv')} - <div class="flex flex-row-reverse w-full"> - <div class="flex items-baseline"> - <label for="csvSeparatorChar" class="text-2xs text-secondary">Separator</label> - - <div class="w-12 ml-2 mr-2"> - <select class="h-8" bind:value={csvSeparatorChar} onchange={(e) => mountGrid()}> - <option value=",">,</option> - <option value=";">;</option> - <option value="\t">\t</option> - <option value="|">|</option> - </select> - </div> - </div> - </div> - {/if} - {#if !disable_download && !s3resource.endsWith('.csv')} - {@const csvApiPath = appPath - ? `/w/${workspaceId}/apps_u/download_s3_parquet_file_as_csv/${appPath}?file_key=${encodeURIComponent(s3resource)}${storage ? `&storage=${storage}` : ''}${presigned ? `&${presigned}` : ''}` - : `/w/${workspaceId}/job_helpers/download_s3_parquet_file_as_csv?file_key=${encodeURIComponent(s3resource)}${storage ? `&storage=${storage}` : ''}`} - {@const csvName = (s3resource.split('/').pop() ?? 'download') + '.csv'} - {#if shouldDownloadViaClient()} - <button - class="text-secondary w-full text-right underline text-2xs whitespace-nowrap" - onclick={() => downloadViaClient(csvApiPath, csvName)} - ><div class="flex flex-row-reverse gap-2 items-center"><Download size={12} /> CSV</div - ></button - > - {:else} - <a - target="_blank" - href="/api{csvApiPath}" - class="text-secondary w-full text-right underline text-2xs whitespace-nowrap" - ><div class="flex flex-row-reverse gap-2 items-center"><Download size={12} /> CSV</div></a - > - {/if} - {/if} - - {#if nbRows != undefined} - <div class="text-secondary ml-0.5 text-2xs">{nbRows} rows</div> - {:else} - <Loader2 class="animate-spin ml-0.5" size={12} /> - {/if} - <div - class="ag-theme-alpine shadow-sm h-full" - class:ag-theme-alpine-dark={darkMode} - style="height: 600px;" - > - {#if error} - <div class="text-red-500">{error}</div> - <div>Try changing separator to fix it</div> - {/if} - <div bind:this={eGui} style="height:100%; "></div> - </div> -</div> - -<!-- <div class="flex gap-1 absolute bottom-1 right-2 text-sm text-secondary" - >{firstRow}{'->'}{lastRow + 1} of {datasource?.rowCount} rows</div -> --> diff --git a/frontend/src/lib/components/RemoteDeployConnect.svelte b/frontend/src/lib/components/RemoteDeployConnect.svelte index d5824a4f2e..ef4421d457 100644 --- a/frontend/src/lib/components/RemoteDeployConnect.svelte +++ b/frontend/src/lib/components/RemoteDeployConnect.svelte @@ -144,7 +144,7 @@ <div class="flex flex-col gap-2"> <a class="text-xs flex flex-row items-center gap-1 w-fit" - href="{target.base_url}/#user-settings" + href="{target.base_url}/#user-settings-tokens" target="_blank" rel="noopener noreferrer" > diff --git a/frontend/src/lib/components/S3FilePreview.svelte b/frontend/src/lib/components/S3FilePreview.svelte index 4635d4f6c7..360b4e5940 100644 --- a/frontend/src/lib/components/S3FilePreview.svelte +++ b/frontend/src/lib/components/S3FilePreview.svelte @@ -322,7 +322,7 @@ <select class="h-8" bind:value={csvSeparatorChar} onchange={onCsvControlsChanged}> <option value=",">,</option> <option value=";">;</option> - <option value="\t">\t</option> + <option value={'\t'}>\t</option> <option value="|">|</option> </select> </div> diff --git a/frontend/src/lib/components/ScriptBuilder.svelte b/frontend/src/lib/components/ScriptBuilder.svelte index 29c5b79797..ed76ca4890 100644 --- a/frontend/src/lib/components/ScriptBuilder.svelte +++ b/frontend/src/lib/components/ScriptBuilder.svelte @@ -30,6 +30,7 @@ import OpenInSessionButton, { type OpenInSessionSource } from './sessions/OpenInSessionButton.svelte' + import { assertDraftSaved } from './sessions/pageDrawerSession' import { defaultScripts, enterpriseLicense, @@ -1071,17 +1072,19 @@ // discardIf baseline, safe only when there is none. async function persistDraftForSession(): Promise<void> { await saveDraft() - if (opWorkspace && userDraftPath && savedScript?.no_deployed === true) { + if (!opWorkspace || !userDraftPath) return + if (savedScript?.no_deployed === true) { await UserDraft.forcePersist('script', userDraftPath, { workspace: opWorkspace }) } + assertDraftSaved({ workspace: opWorkspace, itemKind: 'script', path: userDraftPath }) } const sessionOpen: OpenInSessionSource | undefined = $derived( - userDraftPath + indicatorPath ? { - // URL draft path the editor loads/saves by, not the friendly + // Draft path the editor loads/saves by, not the friendly // `script.path` (a new script's has no row → "not found"). - target: { kind: 'script', path: userDraftPath }, + target: { kind: 'script', path: indicatorPath }, workspaceId: opWorkspace ?? undefined, beforeOpen: persistDraftForSession } @@ -2404,6 +2407,7 @@ bind:this={scriptEditor} bind:schema={script.schema} path={script.path} + storagePath={indicatorPath} bind:code={script.content} timeout={script.timeout} tag={script.tag} diff --git a/frontend/src/lib/components/ScriptEditor.svelte b/frontend/src/lib/components/ScriptEditor.svelte index 95d41a182f..31c442993e 100644 --- a/frontend/src/lib/components/ScriptEditor.svelte +++ b/frontend/src/lib/components/ScriptEditor.svelte @@ -2763,6 +2763,10 @@ lineNumbersMinChars={4} folding {path} + codeSource={customUi?.editorBar?.aiGen != false && + (inSessionPane || SUPPORTED_CHAT_SCRIPT_LANGUAGES.includes(lang ?? '')) + ? { kind: 'script', path: path ?? '', part: activeModuleTab ?? undefined } + : undefined} bind:code={editorCode} bind:websocketAlive bind:this={editor} diff --git a/frontend/src/lib/components/SuperadminSettingsInner.svelte b/frontend/src/lib/components/SuperadminSettingsInner.svelte index 3fba7e887e..5193a20942 100644 --- a/frontend/src/lib/components/SuperadminSettingsInner.svelte +++ b/frontend/src/lib/components/SuperadminSettingsInner.svelte @@ -57,6 +57,7 @@ import InstanceAISettings from './instanceSettings/InstanceAISettings.svelte' import ExternalJwtTokens from './instanceSettings/ExternalJwtTokens.svelte' import GuestActivityList from './instanceSettings/GuestActivityList.svelte' + import TokenReview from './instanceSettings/TokenReview.svelte' import { Alert, Skeleton } from '$lib/components/common' let filter = $state('') @@ -98,15 +99,24 @@ let editWrappers: Record<string, HTMLDivElement> = $state({}) let activeOnly = $state(false) + // Who has two-factor authentication, fetched beside the list. Undefined on a build without + // two-factor support, which hides the column. + let totp = $state<{ required: boolean; users: Set<string> } | undefined>(undefined) + async function listUsers(activeOnly: boolean): Promise<void> { - users = await UserService.listUsersAsSuperAdmin({ perPage: 100000, activeOnly: activeOnly }) + const [list, enabled] = await Promise.all([ + UserService.listUsersAsSuperAdmin({ perPage: 100000, activeOnly: activeOnly }), + UserService.listTotpEnabledUsers().catch(() => undefined) + ]) + users = list + totp = enabled && { required: enabled.required, users: new Set(enabled.users) } } $effect(() => { listUsers(activeOnly) }) - let usersSubTab: 'users' | 'ext_jwt' | 'guests' = $state('users') + let usersSubTab: 'users' | 'ext_jwt' | 'guests' | 'tokens' = $state('users') let guestList: GuestList | undefined = $state(undefined) let guestHasMore = $state(true) let guestLoading = $state(false) @@ -382,6 +392,7 @@ <Tab value="ext_jwt" label="External JWTs" /> {/if} <Tab value="guests" label="Guests" /> + <Tab value="tokens" label="Token review" /> </Tabs> {#if usersListShown} @@ -437,6 +448,9 @@ {/if} <Cell head>Name</Cell> <Cell head>Auth</Cell> + {#if totp} + <Cell head>2FA</Cell> + {/if} {#if activeOnly} <Cell head>Kind</Cell> {/if} @@ -510,6 +524,17 @@ ><span title={login_type} class="truncate block">{login_type}</span ></Cell > + {#if totp} + <Cell> + {#if login_type != 'password'} + <span class="text-secondary">–</span> + {:else if totp.users.has(email)} + On + {:else} + <span class="text-secondary">Off</span> + {/if} + </Cell> + {/if} {#if activeOnly} <Cell> <span> @@ -679,6 +704,8 @@ value={name} {username} {email} + totpEnabled={totp?.users.has(email) ?? false} + totpRequired={totp?.required ?? false} on:refresh={() => { listUsers(activeOnly) }} @@ -768,7 +795,8 @@ <Cell colspan={5 + (automateUsernameCreation ? 1 : 0) + - (activeOnly ? 1 : 0)} + (activeOnly ? 1 : 0) + + (totp ? 1 : 0)} > <Button variant="subtle" @@ -800,6 +828,8 @@ loadExtJwtPage(1) }} /> + {:else if usersSubTab === 'tokens'} + <TokenReview /> {:else if usersSubTab === 'guests' && !guestList} {#if guestLoading} <Skeleton layout={[[2], 1, [8]]} /> diff --git a/frontend/src/lib/components/TaggedTextInput.svelte b/frontend/src/lib/components/TaggedTextInput.svelte index 9f19195b85..be4b7c8e97 100644 --- a/frontend/src/lib/components/TaggedTextInput.svelte +++ b/frontend/src/lib/components/TaggedTextInput.svelte @@ -26,6 +26,13 @@ let contentEditableDiv: HTMLDivElement let isUpdating = false + /** A fresh global copy of `regex` for an exec loop, keeping its other flags (`u`, `i`). + * Not sticky: a sticky scan stops at the first text that is not a match. */ + function globalCopy(regex: RegExp): RegExp { + const flags = regex.flags.replace('y', '') + return new RegExp(regex, flags.includes('g') ? flags : flags + 'g') + } + $effect(() => { if (!value.trim() && value !== '') value = '' }) @@ -37,7 +44,9 @@ const currentText = getTextContent() if (currentText !== value) { updateDisplay(value) - if (!_preventCursorMoveOnNextSync) { + // Placing the caret focuses this input: never take focus from another field + // that wrote the value, such as a table's column filter. + if (!_preventCursorMoveOnNextSync && !typingElsewhere()) { restoreCursor(value.length) const cursorPos = getCursorPosition() updateCurrentTag(cursorPos) @@ -47,6 +56,15 @@ _preventCursorMoveOnNextSync = false }) + function typingElsewhere(): boolean { + const active = document.activeElement + return ( + active instanceof HTMLElement && + !contentEditableDiv.contains(active) && + active.matches('input, textarea, select, [contenteditable]:not([contenteditable="false"])') + ) + } + export function preventCursorMoveOnNextSync() { _preventCursorMoveOnNextSync = true } @@ -70,7 +88,7 @@ // Find all highlight matches in the raw text const hlMatches: Array<{ start: number; end: number; classes: string }> = [] for (const hl of highlights) { - const regex = new RegExp(hl.regex, 'g') + const regex = globalCopy(hl.regex) let m while ((m = regex.exec(rawText)) !== null) { hlMatches.push({ start: m.index, end: m.index + m[0].length, classes: hl.classes }) @@ -111,7 +129,7 @@ const matches: Array<{ start: number; end: number; tagIndex: number }> = [] tags.forEach((tag, tagIndex) => { - const regex = new RegExp(tag.regex, 'g') + const regex = globalCopy(tag.regex) let match while ((match = regex.exec(text)) !== null) { matches.push({ @@ -251,7 +269,7 @@ // Find all tag positions const tagPositions: Array<{ start: number; end: number }> = [] for (const tag of tags) { - const regex = new RegExp(tag.regex, 'g') + const regex = globalCopy(tag.regex) let match while ((match = regex.exec(value)) !== null) { tagPositions.push({ @@ -293,7 +311,7 @@ let currentTag: { id: string } | null = null for (const tag of tags) { - const regex = new RegExp(tag.regex, 'g') + const regex = globalCopy(tag.regex) let match while ((match = regex.exec(value)) !== null) { const start = match.index diff --git a/frontend/src/lib/components/TimeAgo.svelte b/frontend/src/lib/components/TimeAgo.svelte index 1e5515f144..844cac69c5 100644 --- a/frontend/src/lib/components/TimeAgo.svelte +++ b/frontend/src/lib/components/TimeAgo.svelte @@ -168,8 +168,11 @@ // Original mode const nbSecondsAgo = secondsAgo(date) - if (nbSecondsAgo < 600) { + if (nbSecondsAgo < 60) { return `${nbSecondsAgo}s ago` + } else if (nbSecondsAgo < 600) { + const mins = Math.floor(nbSecondsAgo / 60) + return `${mins} min${mins !== 1 ? 's' : ''} ago` } else if (isToday(date)) { isRecent = false return `today at ${date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}` diff --git a/frontend/src/lib/components/TimelineBar.svelte b/frontend/src/lib/components/TimelineBar.svelte index 43c72a9c8b..a76a1e17e5 100644 --- a/frontend/src/lib/components/TimelineBar.svelte +++ b/frontend/src/lib/components/TimelineBar.svelte @@ -4,7 +4,8 @@ import Popover from './Popover.svelte' interface Props { - position?: 'center' | 'left' | 'right' + /** `none`: a middle piece of a bar split in several. */ + position?: 'center' | 'left' | 'right' | 'none' total: number min: number | undefined started_at: number | undefined @@ -61,7 +62,9 @@ ? 'rounded-l-md' : position == 'right' ? 'rounded-r-md' - : 'rounded-md'} center-center text-white text-2xs whitespace-nowrap hover:outline outline-1 outline-black" + : position == 'none' + ? '' + : 'rounded-md'} center-center text-white text-2xs whitespace-nowrap hover:outline outline-1 outline-black" > {#snippet text()} {#if tooltip} diff --git a/frontend/src/lib/components/UserOffboardingModal.svelte b/frontend/src/lib/components/UserOffboardingModal.svelte index c4dbbc537c..8eeab997a4 100644 --- a/frontend/src/lib/components/UserOffboardingModal.svelte +++ b/frontend/src/lib/components/UserOffboardingModal.svelte @@ -4,12 +4,13 @@ import { apiErrorMessage, classNames } from '$lib/utils' import { AlertTriangle, CornerDownLeft, Loader2 } from 'lucide-svelte' import { UserService, FolderService } from '$lib/gen' - import type { OffboardPreview } from '$lib/gen/types.gen' + import type { OffboardPathConflict, OffboardPreview } from '$lib/gen/types.gen' import { workspaceStore } from '$lib/stores' import { sendUserToast } from '$lib/toast' import Toggle from '$lib/components/Toggle.svelte' import OffboardWorkspaceSection from './OffboardWorkspaceSection.svelte' - import { countPaths } from './offboarding-utils' + import OffboardConflictList from './OffboardConflictList.svelte' + import { countPaths, withoutConflict } from './offboarding-utils' type Props = { open: boolean @@ -24,7 +25,7 @@ let preview = $state(undefined as OffboardPreview | undefined) let loading = $state(false) let submitting = $state(false) - let conflicts: string[] = $state([]) + let conflicts: OffboardPathConflict[] = $state([]) let doReassign = $state(true) let targetKind: 'user' | 'folder' = $state('user') @@ -117,8 +118,8 @@ delete_user: deleteUser } }) - if (result.conflicts && result.conflicts.length > 0) { - conflicts = result.conflicts + if (result.conflict_items && result.conflict_items.length > 0) { + conflicts = result.conflict_items } else { sendUserToast( deleteUser @@ -221,17 +222,10 @@ {/if} {#if conflicts.length > 0} - <Alert type="error" title="Path conflicts detected"> - <p class="text-xs mb-1" - >These items already exist at the target. Rename or delete them, or choose a - different user/folder.</p - > - <ul class="text-xs list-disc list-inside max-h-32 overflow-y-auto"> - {#each conflicts as conflict, i (i)} - <li>{conflict}</li> - {/each} - </ul> - </Alert> + <OffboardConflictList + {conflicts} + onResolved={(c) => (conflicts = withoutConflict(conflicts, c))} + /> {/if} </div> {/if} diff --git a/frontend/src/lib/components/UserSettings.svelte b/frontend/src/lib/components/UserSettings.svelte deleted file mode 100644 index 8f64009b37..0000000000 --- a/frontend/src/lib/components/UserSettings.svelte +++ /dev/null @@ -1,148 +0,0 @@ -<script lang="ts"> - import Drawer from '$lib/components/common/drawer/Drawer.svelte' - import DrawerContent from '$lib/components/common/drawer/DrawerContent.svelte' - import Version from './Version.svelte' - import DarkModeToggle from './sidebar/DarkModeToggle.svelte' - import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte' - import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte' - import TokensTable from './settings/TokensTable.svelte' - import { createEventDispatcher, tick } from 'svelte' - import CreateToken from './settings/CreateToken.svelte' - import UserInfoSettings from './settings/UserInfoSettings.svelte' - import AIUserSettings from './settings/AIUserSettings.svelte' - import AiUsagePanel from './workspaceSettings/AiUsagePanel.svelte' - import { copilotInfo, copilotWorkspace } from '$lib/aiStore' - import { - getDarkModeVariant, - setDarkModeVariant, - type DarkModeVariant - } from '$lib/darkModeVariant' - - interface Props { - scopes?: string[] | undefined - newTokenLabel?: string | undefined - newTokenWorkspace?: string | undefined - newToken?: string | undefined - showMcpMode?: boolean - } - - let { - scopes = undefined, - newTokenLabel = undefined, - newTokenWorkspace = undefined, - newToken = $bindable(undefined), - showMcpMode = false - }: Props = $props() - - let drawer: Drawer | undefined = $state() - let mcpSection: HTMLDivElement | undefined = $state() - let tokensTable: TokensTable | undefined = $state() - let darkVariant = $state<DarkModeVariant>(getDarkModeVariant()) - - const dispatch = createEventDispatcher() - - export async function openDrawer(mcpMode: boolean = false) { - drawer?.openDrawer() - if (mcpMode) { - await tick() - mcpSection?.scrollIntoView({ block: 'start' }) - } - } - - export function closeDrawer() { - drawer?.closeDrawer() - removeHash() - } - - function removeHash() { - window.location.hash = '' - } - - function handleTokenCreated(token: string) { - newToken = token - dispatch('tokenCreated', token) - } -</script> - -<Drawer - bind:this={drawer} - size="900px" - on:open={() => (darkVariant = getDarkModeVariant())} - on:close={removeHash} -> - <DrawerContent title="User settings" on:close={closeDrawer}> - <div class="flex flex-col gap-6 pb-8"> - {#if scopes == undefined} - <div - class="flex flex-row justify-between items-start gap-2 border border-border-light p-4 rounded-md" - > - <div class="flex flex-col gap-2"> - <div class="font-semibold text-emphasis text-xs flex items-center"> - Theme <DarkModeToggle forcedDarkMode={false} /> - </div> - <div class="flex items-center gap-2"> - <span class="text-xs text-secondary">Dark variant</span> - <ToggleButtonGroup - selected={darkVariant} - class="w-fit" - onSelected={(v) => { - darkVariant = v - setDarkModeVariant(v) - }} - > - {#snippet children({ item })} - <ToggleButton value="default" label="Default" size="sm" {item} /> - <ToggleButton value="github" label="GitHub" size="sm" {item} /> - {/snippet} - </ToggleButtonGroup> - </div> - </div> - <div class="text-xs text-emphasis flex-col flex"> - Windmill <Version /> - </div> - </div> - <div class="grid grid-cols-1 lg:grid-cols-2 w-full gap-4"> - <div class="min-w-0"> - <UserInfoSettings /> - </div> - <div class="min-w-0"> - <AIUserSettings /> - </div> - </div> - <!-- Keyed on the workspace `copilotInfo` reflects, not on `$workspaceStore`, - which is ahead of it while a switch loads: pricing usage from one - workspace with another's rates would silently misstate it. --> - {#if $copilotWorkspace} - <AiUsagePanel - workspace={$copilotWorkspace} - modelPricing={$copilotInfo.modelPricing ?? {}} - scope="self" - /> - {/if} - {/if} - - {#if showMcpMode} - <div bind:this={mcpSection} class="flex flex-col p-4 border border-border-light rounded-md"> - <h2 class="text-emphasis text-sm font-semibold mb-1"> - Build and run from your AI client - </h2> - <div class="text-xs text-secondary mb-2"> - Connect Claude, ChatGPT or Cursor to Windmill over MCP: build scripts, flows and apps, - run your automations and check their runs, from your chat. - </div> - <CreateToken mcpOnly onTokenCreated={() => tokensTable?.listTokens()} /> - </div> - {/if} - - <div class="grow min-h-0"> - <TokensTable - bind:this={tokensTable} - defaultNewTokenLabel={newTokenLabel} - defaultNewTokenWorkspace={newTokenWorkspace} - {scopes} - onTokenCreated={handleTokenCreated} - /> - </div> - </div> - </DrawerContent> -</Drawer> diff --git a/frontend/src/lib/components/account/AccountSettingsDrawers.svelte b/frontend/src/lib/components/account/AccountSettingsDrawers.svelte new file mode 100644 index 0000000000..c0410814d6 --- /dev/null +++ b/frontend/src/lib/components/account/AccountSettingsDrawers.svelte @@ -0,0 +1,50 @@ +<!-- +@component +The account settings drawers, one per concern, opened by `#user-settings[-<panel>]`. +At most one is open: opening another closes the current one without clearing the hash. +--> +<script lang="ts"> + import { + parseAccountSettingsHash, + type AccountSettingsPanel + } from '$lib/components/sidebar/settings' + import ProfileDrawer from './ProfileDrawer.svelte' + import TokensDrawer from './TokensDrawer.svelte' + import AiSettingsDrawer from './AiSettingsDrawer.svelte' + import McpDrawer from './McpDrawer.svelte' + + let active = $state<AccountSettingsPanel | undefined>(undefined) + + export function open(panel: AccountSettingsPanel) { + active = panel + } + + export function openFromHash(hash: string) { + const panel = parseAccountSettingsHash(hash) + if (panel) active = panel + } + + function binding(panel: AccountSettingsPanel) { + return { + get: () => active === panel, + set: (value: boolean) => { + if (value) { + active = panel + } else if (active === panel) { + active = undefined + if (parseAccountSettingsHash(window.location.hash)) window.location.hash = '' + } + } + } + } + + const profile = binding('profile') + const tokens = binding('tokens') + const ai = binding('ai') + const mcp = binding('mcp') +</script> + +<ProfileDrawer bind:open={profile.get, profile.set} /> +<TokensDrawer bind:open={tokens.get, tokens.set} /> +<AiSettingsDrawer bind:open={ai.get, ai.set} /> +<McpDrawer bind:open={mcp.get, mcp.set} /> diff --git a/frontend/src/lib/components/account/AiSettingsDrawer.svelte b/frontend/src/lib/components/account/AiSettingsDrawer.svelte new file mode 100644 index 0000000000..38bba1d30c --- /dev/null +++ b/frontend/src/lib/components/account/AiSettingsDrawer.svelte @@ -0,0 +1,32 @@ +<script lang="ts"> + import { Drawer, DrawerContent } from '$lib/components/common' + import AIUserSettings from '$lib/components/settings/AIUserSettings.svelte' + import AiUsagePanel from '$lib/components/workspaceSettings/AiUsagePanel.svelte' + import { copilotInfo, copilotWorkspace } from '$lib/aiStore' + import { accountSettingsHref } from '$lib/components/sidebar/settings' + + let { open = $bindable() }: { open?: boolean } = $props() +</script> + +<Drawer bind:open size="800px"> + <DrawerContent title="AI settings" on:close={() => (open = false)}> + <div class="flex flex-col gap-6 pb-8"> + <div class="text-xs text-secondary"> + To use Windmill from Claude, ChatGPT or Cursor, see + <a href={accountSettingsHref('mcp')}>Connect an AI client</a>. + </div> + <AIUserSettings /> + <!-- Keyed on the workspace `copilotInfo` reflects, not on `$workspaceStore`: + a session acting on another workspace loads that workspace's AI config + while navigation stays put, and pricing usage from one workspace with + another's rates would silently misstate it. --> + {#if $copilotWorkspace} + <AiUsagePanel + workspace={$copilotWorkspace} + modelPricing={$copilotInfo.modelPricing ?? {}} + scope="self" + /> + {/if} + </div> + </DrawerContent> +</Drawer> diff --git a/frontend/src/lib/components/account/McpDrawer.svelte b/frontend/src/lib/components/account/McpDrawer.svelte new file mode 100644 index 0000000000..164c6524ad --- /dev/null +++ b/frontend/src/lib/components/account/McpDrawer.svelte @@ -0,0 +1,31 @@ +<script lang="ts"> + import { Drawer, DrawerContent } from '$lib/components/common' + import CreateToken from '$lib/components/settings/CreateToken.svelte' + import { accountSettingsHref } from '$lib/components/sidebar/settings' + + let { open = $bindable() }: { open?: boolean } = $props() +</script> + +<Drawer bind:open size="800px"> + <DrawerContent + title="Connect an AI client" + documentationLink="https://www.windmill.dev/docs/core_concepts/mcp" + on:close={() => (open = false)} + > + <div class="flex flex-col gap-2 pb-8"> + <div class="text-xs text-secondary mb-2"> + Connect Claude, ChatGPT or Cursor to Windmill over MCP: build scripts, flows and apps, run + your automations and check their runs, from your chat. + </div> + <CreateToken mcpOnly onTokenCreated={() => {}} /> + <div class="text-xs text-secondary"> + Tokens you create here are listed, and can be revoked, in + <a href={accountSettingsHref('tokens')}>Tokens</a>. + </div> + <div class="text-xs text-secondary"> + Windmill's own AI assistant is configured in + <a href={accountSettingsHref('ai')}>AI settings</a>. + </div> + </div> + </DrawerContent> +</Drawer> diff --git a/frontend/src/lib/components/account/ProfileDrawer.svelte b/frontend/src/lib/components/account/ProfileDrawer.svelte new file mode 100644 index 0000000000..faa4d34aa9 --- /dev/null +++ b/frontend/src/lib/components/account/ProfileDrawer.svelte @@ -0,0 +1,63 @@ +<script lang="ts"> + import { Drawer, DrawerContent, ListRow } from '$lib/components/common' + import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte' + import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte' + import DarkModeToggle from '$lib/components/sidebar/DarkModeToggle.svelte' + import Version from '$lib/components/Version.svelte' + import UserInfoSettings from '$lib/components/settings/UserInfoSettings.svelte' + import { + getDarkModeVariant, + setDarkModeVariant, + type DarkModeVariant + } from '$lib/darkModeVariant' + import { ACCOUNT_SETTINGS_LINKS } from './accountSettingsLinks' + + let { open = $bindable() }: { open?: boolean } = $props() + + let darkVariant = $state<DarkModeVariant>(getDarkModeVariant()) + + const otherLinks = ACCOUNT_SETTINGS_LINKS.filter((l) => l.panel !== 'profile') +</script> + +<Drawer bind:open size="600px" on:open={() => (darkVariant = getDarkModeVariant())}> + <DrawerContent title="Profile" on:close={() => (open = false)}> + <div class="flex flex-col gap-6 pb-8"> + <UserInfoSettings /> + + <div class="flex flex-col gap-1"> + <div class="text-xs text-emphasis font-semibold flex items-center"> + Theme <DarkModeToggle forcedDarkMode={false} /> + </div> + <div class="flex items-center gap-2"> + <span class="text-xs text-secondary">Dark variant</span> + <ToggleButtonGroup + selected={darkVariant} + class="w-fit" + onSelected={(v) => { + darkVariant = v + setDarkModeVariant(v) + }} + > + {#snippet children({ item })} + <ToggleButton value="default" label="Default" size="sm" {item} /> + <ToggleButton value="github" label="GitHub" size="sm" {item} /> + {/snippet} + </ToggleButtonGroup> + </div> + </div> + + <div class="flex flex-col gap-1"> + <h2 class="text-emphasis text-sm font-semibold mb-1">More account settings</h2> + {#each otherLinks as link (link.panel)} + <ListRow onClick={() => (window.location.hash = link.href)}> + {#snippet icon()}<link.icon size={16} />{/snippet} + {#snippet title()}{link.label}{/snippet} + {#snippet subtitle()}{link.description}{/snippet} + </ListRow> + {/each} + </div> + + <div class="flex items-center gap-1 text-xs text-secondary">Windmill <Version /></div> + </div> + </DrawerContent> +</Drawer> diff --git a/frontend/src/lib/components/account/TokensDrawer.svelte b/frontend/src/lib/components/account/TokensDrawer.svelte new file mode 100644 index 0000000000..9b65b79015 --- /dev/null +++ b/frontend/src/lib/components/account/TokensDrawer.svelte @@ -0,0 +1,47 @@ +<script lang="ts"> + import { Drawer, DrawerContent } from '$lib/components/common' + import TokensTable from '$lib/components/settings/TokensTable.svelte' + + interface Props { + open?: boolean + /** Given, the drawer mints a token restricted to these scopes, for the caller to use. */ + scopes?: string[] + newTokenLabel?: string + newTokenWorkspace?: string + newToken?: string + onTokenCreated?: (token: string) => void + } + + let { + open = $bindable(), + scopes = undefined, + newTokenLabel = undefined, + newTokenWorkspace = undefined, + newToken = $bindable(undefined), + onTokenCreated + }: Props = $props() + + export function openDrawer() { + open = true + } + + export function closeDrawer() { + open = false + } +</script> + +<Drawer bind:open size="900px"> + <DrawerContent title="Tokens" on:close={closeDrawer}> + <div class="pb-8"> + <TokensTable + defaultNewTokenLabel={newTokenLabel} + defaultNewTokenWorkspace={newTokenWorkspace} + {scopes} + onTokenCreated={(token) => { + newToken = token + onTokenCreated?.(token) + }} + /> + </div> + </DrawerContent> +</Drawer> diff --git a/frontend/src/lib/components/account/accountSettingsLinks.ts b/frontend/src/lib/components/account/accountSettingsLinks.ts new file mode 100644 index 0000000000..792c3b0d8a --- /dev/null +++ b/frontend/src/lib/components/account/accountSettingsLinks.ts @@ -0,0 +1,27 @@ +import { KeyRound, Plug, Sparkles, UserCog } from 'lucide-svelte' +import { accountSettingsHref, type AccountSettingsPanel } from '$lib/components/sidebar/settings' + +export type AccountSettingsLink = { + panel: AccountSettingsPanel + label: string + description: string + href: string + icon: typeof UserCog +} + +function link( + panel: AccountSettingsPanel, + label: string, + description: string, + icon: typeof UserCog +): AccountSettingsLink { + return { panel, label, description, href: accountSettingsHref(panel), icon } +} + +/** The account settings drawers, in the order every menu lists them. */ +export const ACCOUNT_SETTINGS_LINKS: AccountSettingsLink[] = [ + link('profile', 'Profile', 'Email, password and theme', UserCog), + link('tokens', 'Tokens', 'Personal access tokens for the API and the CLI', KeyRound), + link('ai', 'AI settings', 'Completions, custom prompts and your AI usage', Sparkles), + link('mcp', 'Connect an AI client', 'Use Windmill from Claude, ChatGPT or Cursor over MCP', Plug) +] diff --git a/frontend/src/lib/components/approvals/MinimalApprovalSkin.svelte b/frontend/src/lib/components/approvals/MinimalApprovalSkin.svelte index a4ecde8ffb..b77d7f11d4 100644 --- a/frontend/src/lib/components/approvals/MinimalApprovalSkin.svelte +++ b/frontend/src/lib/components/approvals/MinimalApprovalSkin.svelte @@ -205,7 +205,10 @@ > <span class="text-2xs font-normal text-secondary"> {#if status === 'pending' && approvalInfo.approvers.length > 0} - Already approved by {approvalInfo.approvers.map((a) => a.approver).join(', ')} + {approvalInfo.required_events + ? `${approvalInfo.approvers.length} of ${approvalInfo.required_events} approvals:` + : 'Already approved by'} + {approvalInfo.approvers.map((a) => a.approver).join(', ')} {/if} </span> {#if isWorkspaceMember} diff --git a/frontend/src/lib/components/apps/components/display/dbtable/InsertRow.svelte b/frontend/src/lib/components/apps/components/display/dbtable/InsertRow.svelte index 4910a824ce..2709661167 100644 --- a/frontend/src/lib/components/apps/components/display/dbtable/InsertRow.svelte +++ b/frontend/src/lib/components/apps/components/display/dbtable/InsertRow.svelte @@ -14,7 +14,7 @@ init(wasmUrl) - import { argSigToJsonSchemaType } from 'windmill-utils-internal' + import { argSigToJsonSchemaType } from 'windmill-utils-internal/parse/parse-schema' import SchemaForm from '$lib/components/SchemaForm.svelte' import { untrack } from 'svelte' import Toggle from '$lib/components/Toggle.svelte' diff --git a/frontend/src/lib/components/apps/editor/AppSettingsDrawer.svelte b/frontend/src/lib/components/apps/editor/AppSettingsDrawer.svelte index dd332a8f93..149d341942 100644 --- a/frontend/src/lib/components/apps/editor/AppSettingsDrawer.svelte +++ b/frontend/src/lib/components/apps/editor/AppSettingsDrawer.svelte @@ -108,7 +108,9 @@ {:else} <Alert type="warning" title="Not isolated" size="xs"> The app's frontend code runs with each viewer's full Windmill permissions. A future version - will ask viewers to approve this. Keep isolation off only if the app needs it. + will ask viewers to approve this. Keep isolation off only if the app needs it. Viewers who are + not members of this workspace (public link, guests, other workspaces) always get the isolated + render, whatever this setting says. Test a public app from a private window. </Alert> {/if} {/snippet} @@ -232,7 +234,7 @@ <SettingToggle setting="sandbox" label="Sandbox isolation" - tooltip="Controls what the app's browser-side code can reach in each viewer's browser, separately from who its runnables run as. A sandboxed app gets a narrowly scoped token on every surface, public URL and in-workspace. On by default for new apps. Turn it off only if the app needs IndexedDB, third-party sign-in or OAuth redirects." + tooltip="Controls what the app's browser-side code can reach in each viewer's browser, separately from who its runnables run as. A sandboxed app gets a narrowly scoped token on every surface, public URL and in-workspace. On by default for new apps. Turn it off only if the app needs IndexedDB, third-party sign-in or OAuth redirects. Viewers who are not members of this workspace (public link, guests, other workspaces) always get the isolated render, whatever this setting says." checked={composeOnlyApps || policy.sandbox == true} disabled={composeOnlyApps} hint={composeOnlyApps || policy.sandbox != true ? sandboxHint : undefined} diff --git a/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte b/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte index 1795cbe841..008c26638d 100644 --- a/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte +++ b/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte @@ -10,6 +10,7 @@ * scoped embed token / opaque isolation. */ import { sendUserToast } from '$lib/toast' + import { encodePathParam } from '$lib/apiPathParams' import PublicApp from '$lib/components/apps/editor/PublicApp.svelte' import PublicAppFrame from '$lib/components/apps/editor/PublicAppFrame.svelte' import PageHeaderContent from '$lib/components/PageHeaderContent.svelte' @@ -124,9 +125,8 @@ headers['Authorization'] = `Bearer ${OpenAPI.TOKEN}` } const consent = opts?.sdkConsent ? '?sdk_consent=true' : '' - const res = await fetch(`${OpenAPI.BASE}/w/${workspace}/apps/embed_token/p/${path}${consent}`, { - headers - }) + const url = `${OpenAPI.BASE}/w/${encodePathParam('workspace', workspace)}/apps/embed_token/p/${encodePathParam('path', path)}${consent}` + const res = await fetch(url, { headers }) if (!res.ok) { // Minted for the deployed app under the caller's RLS: a 404 is "nothing deployed here" or // "not visible to this member", the same reading as `getAppLiteByPath`'s 404 below. diff --git a/frontend/src/lib/components/apps/editor/PublicAppFrame.svelte b/frontend/src/lib/components/apps/editor/PublicAppFrame.svelte index 4c391c0336..05cbdfc441 100644 --- a/frontend/src/lib/components/apps/editor/PublicAppFrame.svelte +++ b/frontend/src/lib/components/apps/editor/PublicAppFrame.svelte @@ -14,8 +14,10 @@ * - Raw, sandboxed: rendered directly here as a **single** opaque bundle iframe * (the author bundle is already isolated in its own opaque iframe); no opaque * viewer / embed token needed. - * - Unsandboxed (default): the app runs same-origin with the viewer's full - * session, the pre-isolation behavior. Rendered directly here. + * - Unsandboxed: the app runs same-origin with the viewer's full session. + * Rendered directly here. Only for a member of the app's workspace viewing an + * app its publisher left unsandboxed; the embed-token response decides it, and + * anyone else gets one of the isolated renders above. * * No `PUBLIC_APP_DOMAIN` is required: the opaque origin is, for same-origin-policy * purposes, as foreign to the main app as a different domain. The opaque viewer's @@ -28,6 +30,7 @@ import { onDestroy, onMount, setContext, type Snippet } from 'svelte' import Skeleton from '$lib/components/common/skeleton/Skeleton.svelte' import { goto } from '$app/navigation' + import { parseHttpUrl, toSameOriginRelativePath } from '$lib/navigationTarget' import { WINDMILL_RESERVED_QUERY_PARAMS } from '$lib/utils/queryParams' import { EMBED_NAV_CONTEXT_KEY, type EmbedNav } from '../types' import { loadAppPreview } from './loadAppPreview' @@ -316,10 +319,11 @@ let modeChangeRestarts = 0 const MAX_MODE_CHANGE_RESTARTS = 3 - // WIN-2006: publisher opted this app into sandbox isolation (alpha). When false - // (the default) the app runs same-origin with the viewer's full session — the - // pre-isolation behavior. - let sandboxed = $state(false) + // Whether the server says this viewer gets the isolated render (the publisher + // opted in, or the viewer is not a member of the app's workspace). Read only from + // the embed-token response, and a response without it counts as isolated: the + // app's own policy must never decide this on the client. + let sandboxed = $state(true) // WIN-2006 Variant A: raw apps render single-iframe. The author's bundle is // already isolated in its own opaque iframe (served + CSP-sandboxed by the @@ -371,7 +375,7 @@ try { const resp = await fetchEmbedToken() embedToken = resp.token ?? null - sandboxed = resp.sandbox ?? false + sandboxed = resp.sandbox !== false isRaw = resp.raw_app ?? false appPath = resp.app_path ?? undefined workspaceId = resp.workspace_id ?? undefined @@ -416,7 +420,7 @@ // response's mode would bypass new isolation or leave the viewer // unauthenticated. Start over; bounded so redeploys can't bounce forever. const modeChanged = - (resp.raw_app ?? false) !== wasRaw || (resp.sandbox ?? false) !== wasSandboxed + (resp.raw_app ?? false) !== wasRaw || (resp.sandbox !== false) !== wasSandboxed if (modeChanged) { if (modeChangeRestarts < MAX_MODE_CHANGE_RESTARTS) { modeChangeRestarts++ @@ -428,7 +432,7 @@ status = 'notExists' return false } - sandboxed = resp.sandbox ?? false + sandboxed = resp.sandbox !== false isRaw = resp.raw_app ?? false appPath = resp.app_path ?? appPath workspaceId = resp.workspace_id ?? workspaceId @@ -568,12 +572,16 @@ // the app ran on it pre-sandbox. Same-origin paths use SPA navigation; // full http(s) URLs do a real load (pre-sandbox apps could already do // this via window.location, so it grants nothing new). Everything else — - // javascript:, data:, protocol-relative `//host` — is rejected. + // javascript:, data:, protocol-relative `//host`, and this instance's own + // `/api/` routes, which this page would reach as a same-origin request — is + // rejected. const href = typeof e.data.href === 'string' ? e.data.href : '' - if (href.startsWith('/') && !href.startsWith('//')) { - goto(href) + if (href.startsWith('/')) { + const path = toSameOriginRelativePath(href) + if (path) goto(path) } else if (/^https?:\/\//i.test(href)) { - window.location.href = href + const url = parseHttpUrl(href) + if (url) window.location.href = url.href } } } diff --git a/frontend/src/lib/components/apps/editor/appUtilsS3.ts b/frontend/src/lib/components/apps/editor/appUtilsS3.ts index 15353382cc..9e9228dd59 100644 --- a/frontend/src/lib/components/apps/editor/appUtilsS3.ts +++ b/frontend/src/lib/components/apps/editor/appUtilsS3.ts @@ -117,7 +117,7 @@ export async function getS3File({ // Editor/preview runs execute as the *caller* (Viewer mode), so read their // results back as the caller through the viewer-scoped `job_helpers` endpoint — - // never author-mode — consistent with DisplayResult/ParqetCsvTableRenderer. Only + // never author-mode — consistent with DisplayResult. Only // a deployed app view reads on-behalf of the author via the provenance-gated // `apps_u` endpoint. if (isEditor) { diff --git a/frontend/src/lib/components/apps/editor/publicAppApi.ts b/frontend/src/lib/components/apps/editor/publicAppApi.ts index 674cb0b622..ad35261c57 100644 --- a/frontend/src/lib/components/apps/editor/publicAppApi.ts +++ b/frontend/src/lib/components/apps/editor/publicAppApi.ts @@ -7,6 +7,7 @@ import { OpenAPI } from '$lib/gen/core/OpenAPI' import type { AppWithLastVersion, User } from '$lib/gen/types.gen' import type { UserExt } from '$lib/stores' import { mapUserToUserExt } from '$lib/userExt' +import { encodePathParam } from '$lib/apiPathParams' export type PublicAppValue = AppWithLastVersion & { value: any; workspace_id?: string } @@ -57,7 +58,7 @@ export async function publicGet<T>(path: string): Promise<T> { export async function getUserExtOrUndefined(workspace: string): Promise<UserExt | undefined> { try { return mapUserToUserExt( - await publicGet<User>(`/w/${encodeURI(workspace)}/users/whoami`), + await publicGet<User>(`/w/${encodePathParam('workspace', workspace)}/users/whoami`), workspace ) } catch { diff --git a/frontend/src/lib/components/auditLogs/AuditLogDetails.svelte b/frontend/src/lib/components/auditLogs/AuditLogDetails.svelte index 1289deb222..de7e96fffb 100644 --- a/frontend/src/lib/components/auditLogs/AuditLogDetails.svelte +++ b/frontend/src/lib/components/auditLogs/AuditLogDetails.svelte @@ -62,6 +62,30 @@ </span> </div> {/if} + {#if log.client_ip} + <div class="flex flex-col gap-1"> + <span class="font-semibold text-xs text-emphasis">Client IP</span> + <span class="text-xs break-all">{log.client_ip}</span> + </div> + {/if} + {#if log.peer_ip} + <div class="flex flex-col gap-1"> + <span class="font-semibold text-xs text-emphasis">Forwarded by</span> + <span class="text-xs break-all">{log.peer_ip}</span> + </div> + {/if} + {#if log.forwarded_for} + <div class="flex flex-col gap-1"> + <span class="font-semibold text-xs text-emphasis">Forwarding header</span> + <span class="text-xs break-all font-mono">{log.forwarded_for}</span> + </div> + {/if} + {#if log.user_agent} + <div class="flex flex-col gap-1"> + <span class="font-semibold text-xs text-emphasis">User agent</span> + <span class="text-xs break-all">{log.user_agent}</span> + </div> + {/if} <div class="flex flex-col gap-1"> <span class="font-semibold text-xs text-emphasis">Parameters</span> <div class="text-xs p-2 bg-surface-secondary rounded-md overflow-x-auto"> diff --git a/frontend/src/lib/components/chartjs-wrappers/Chart.svelte b/frontend/src/lib/components/chartjs-wrappers/Chart.svelte index 66739a7859..fa59ca73c4 100644 --- a/frontend/src/lib/components/chartjs-wrappers/Chart.svelte +++ b/frontend/src/lib/components/chartjs-wrappers/Chart.svelte @@ -8,6 +8,7 @@ import 'chart.js/auto' import 'chartjs-adapter-date-fns' import { untrack } from 'svelte' + import { clone } from '$lib/utils' interface Props extends HTMLCanvasAttributes { type: T @@ -28,7 +29,7 @@ chart = new Chart(canvasElem, { type, data: $state.snapshot(data) as typeof data, - options: $state.snapshot(options) as typeof options + options: clone(options) }) }) return () => { diff --git a/frontend/src/lib/components/common/fileDownload/S3ObjectTable.svelte b/frontend/src/lib/components/common/fileDownload/S3ObjectTable.svelte new file mode 100644 index 0000000000..122f618a0d --- /dev/null +++ b/frontend/src/lib/components/common/fileDownload/S3ObjectTable.svelte @@ -0,0 +1,178 @@ +<script lang="ts"> + import { ChevronDown, Download, Loader2 } from 'lucide-svelte' + import { Button } from '$lib/components/common' + import Select from '$lib/components/select/Select.svelte' + import Toggle from '$lib/components/Toggle.svelte' + import type { IDbTableOps } from '$lib/components/dbOps' + import { s3TableOps, serverTableFormat } from '$lib/components/s3TableOps' + import { + setOperatingWorkspace, + useOperatingWorkspace + } from '$lib/components/operatingWorkspace.svelte' + import { downloadViaClient, shouldDownloadViaClient } from '$lib/utils/downloadFile' + + interface Props { + s3object: { s3: string; storage?: string; presigned?: string; disable_download?: boolean } + workspaceId?: string | undefined + /** Set in a deployed app: the file is read through the app-scoped `apps_u/*` routes. */ + appPath?: string | undefined + } + + let { s3object, workspaceId = undefined, appPath = undefined }: Props = $props() + + const operatingWorkspace = useOperatingWorkspace() + // DBTable loads no rows without an operating workspace, and a public app sets none. + setOperatingWorkspace(() => workspaceId) + + const CSV_SEPARATORS = [ + { value: ',', label: ',' }, + { value: ';', label: ';' }, + { value: '\t', label: 'Tab' }, + { value: '|', label: '|' } + ] + // DBTable's search bar, header row and body rows, in px. + const TOOLBAR_HEIGHT = 40 + // Below about this width the toolbar wraps the row count and buttons under the search bar. + const TOOLBAR_WRAP_WIDTH = 480 + const HEADER_HEIGHT = 30 + const ROW_HEIGHT = 34 + const SCROLLBAR = 12 + + let separator: string | undefined = $state(undefined) + let hasHeader = $state(true) + /** The separator the server guessed while none is picked. */ + let detectedSeparator: string | undefined = $state(undefined) + /** Rows in the whole file, kept while a search narrows them so the table keeps its height. */ + let totalRows: number | undefined = $state(undefined) + let width = $state(0) + + // JSON lines are read through the CSV route too, but have no separator or header row. + let isCsv = $derived(/\.(csv|tsv)$/i.test(s3object.s3)) + let isParquet = $derived(serverTableFormat(s3object.s3) === 'parquet') + let workspace = $derived(workspaceId ?? $operatingWorkspace!) + // The server converts the whole file; the table's own export only has the rows it loaded. + let parquetCsvPath = $derived( + appPath + ? `/w/${workspace}/apps_u/download_s3_parquet_file_as_csv/${appPath}?file_key=${encodeURIComponent(s3object.s3)}${s3object.storage ? `&storage=${s3object.storage}` : ''}${s3object.presigned ? `&${s3object.presigned}` : ''}` + : `/w/${workspace}/job_helpers/download_s3_parquet_file_as_csv?file_key=${encodeURIComponent(s3object.s3)}${s3object.storage ? `&storage=${s3object.storage}` : ''}` + ) + let parquetCsvName = $derived((s3object.s3.split('/').pop() ?? 'download') + '.csv') + + let height = $derived( + totalRows === undefined + ? 240 + : Math.min( + 600, + Math.max( + 180, + (width && width < TOOLBAR_WRAP_WIDTH ? 2 : 1) * TOOLBAR_HEIGHT + + HEADER_HEIGHT + + totalRows * ROW_HEIGHT + + SCROLLBAR + ) + ) + ) + + function recordingTotal(ops: IDbTableOps, source: Promise<unknown>): IDbTableOps { + return { + ...ops, + getCount: async (params) => { + const n = await ops.getCount(params) + const filtered = !!params.quicksearch || Object.keys(params.columnFilters ?? {}).length > 0 + // A count from a table the separator, header row or file replaced is not this one's. + if (!filtered && table === source) totalRows = n + return n + } + } + } + + // Lazy: DBTable reaches Monaco, and every page that shows a job result imports this table. + const dbTable = import('$lib/components/DBTable.svelte') + + let table = $derived.by(() => { + const pending = s3TableOps({ + workspace, + fileKey: s3object.s3, + storage: s3object.storage, + csvSeparator: separator, + csvHasHeader: hasHeader, + app: appPath ? { path: appPath, presigned: s3object.presigned } : undefined + }).then((t) => { + // A table superseded while loading must not label the current one. + if (table !== pending) return t as never + detectedSeparator = t.csvSeparator + return dbTable.then((m) => ({ + ...t, + ops: recordingTotal(t.ops, pending), + DBTable: m.default + })) + }) + return pending + }) +</script> + +<div class="flex flex-col gap-1 mt-2"> + {#if isCsv || (isParquet && !s3object.disable_download)} + <div class="flex items-center justify-end gap-4 text-xs text-secondary"> + {#if isCsv} + <div class="flex items-center gap-2"> + <span>Separator</span> + <Select + size="sm" + class="w-20" + clearable + RightIcon={ChevronDown} + items={CSV_SEPARATORS} + bind:value={separator} + placeholder={CSV_SEPARATORS.find((s) => s.value === detectedSeparator)?.label ?? 'Auto'} + /> + </div> + <Toggle size="xs" bind:checked={hasHeader} options={{ right: 'Header row' }} /> + {:else if shouldDownloadViaClient()} + <Button + variant="subtle" + unifiedSize="xs" + startIcon={{ icon: Download }} + onClick={() => downloadViaClient(parquetCsvPath, parquetCsvName)} + > + Download as CSV + </Button> + {:else} + <Button + variant="subtle" + unifiedSize="xs" + startIcon={{ icon: Download }} + href="/api{parquetCsvPath}" + download={parquetCsvName} + > + Download as CSV + </Button> + {/if} + </div> + {/if} + + <div + class="overflow-hidden border rounded-md" + style="height: {height}px" + bind:clientWidth={width} + data-interactive + > + {#await table} + <div class="flex h-full items-center justify-center gap-1 text-2xs text-secondary"> + <Loader2 size={12} class="animate-spin" /> Loading table + </div> + {:then t} + <t.DBTable dbTableOps={t.ops} disableDownload={s3object.disable_download || isParquet} /> + {:catch e} + {@const message = String(e?.body ?? e?.message ?? e)} + <!-- The storage reports an empty file as a failed range read. --> + {#if /Range started at 0 and ended at 0/.test(message)} + <div class="p-3 text-xs text-secondary">This file is empty.</div> + {:else} + <div class="p-3 text-xs text-red-600 dark:text-red-400 break-words"> + Could not read this file as a table: {message} + </div> + {/if} + {/await} + </div> +</div> diff --git a/frontend/src/lib/components/common/image/ExpandableImage.svelte b/frontend/src/lib/components/common/image/ExpandableImage.svelte index 35d54e87ca..f0997711d7 100644 --- a/frontend/src/lib/components/common/image/ExpandableImage.svelte +++ b/frontend/src/lib/components/common/image/ExpandableImage.svelte @@ -25,9 +25,12 @@ title?: string /** Classes for the inline thumbnail — sizing, border, radius. */ class?: string + /** Opens the image in a viewer elsewhere (a session's preview panel), offered as a + * button in the expanded view. */ + onOpen?: () => void } - let { src, alt = '', title, class: className = '' }: Props = $props() + let { src, alt = '', title, class: className = '', onOpen }: Props = $props() let isOpen = $state(false) @@ -69,4 +72,4 @@ }} /> -<ImageViewer bind:isOpen {src} {alt} {title} /> +<ImageViewer bind:isOpen {src} {alt} {title} onOpenInPreview={onOpen} /> diff --git a/frontend/src/lib/components/common/image/ImagePanelViewer.svelte b/frontend/src/lib/components/common/image/ImagePanelViewer.svelte new file mode 100644 index 0000000000..de4097d183 --- /dev/null +++ b/frontend/src/lib/components/common/image/ImagePanelViewer.svelte @@ -0,0 +1,151 @@ +<script lang="ts"> + import { Download, Grid2x2, Maximize, Moon, Sun } from 'lucide-svelte' + import { Button } from '$lib/components/common' + import ZoomControl from './ZoomControl.svelte' + import { useZoomPan } from './zoomPan.svelte' + import { twMerge } from 'tailwind-merge' + import { useIsDarkMode } from '$lib/components/DarkModeObserver.svelte' + + interface Props { + src: string + /** Shown in the header and used as the download's file name. */ + name: string + /** Byte size, shown beside the dimensions when known. */ + bytes?: number + } + + let { src, name, bytes }: Props = $props() + + type Backdrop = 'checker' | 'light' | 'dark' + const BACKDROPS = { + light: { label: 'Light', icon: Sun }, + dark: { label: 'Dark', icon: Moon }, + checker: { label: 'Checkerboard', icon: Grid2x2 } + } as const + + // Room kept around a fitted image so its edges stay visible against the backdrop. + const view = useZoomPan({ margin: { x: 32, y: 32 } }) + // The source that failed, not a flag: a new `src` (the file fixed and re-read) must mount + // the image again, and only the image's own load event could clear a flag. + let failedSrc = $state<string>() + const failed = $derived(failedSrc === src) + // Until the viewer picks one, the backdrop is Windmill's own theme, and follows it. + const isDark = useIsDarkMode() + let chosenBackdrop = $state<Backdrop | undefined>(undefined) + const backdrop = $derived<Backdrop>(chosenBackdrop ?? (isDark.val ? 'dark' : 'light')) + // The cycle starts at the theme's own backdrop, so the first click swaps light and dark. + const backdropCycle = $derived<Backdrop[]>( + isDark.val ? ['dark', 'light', 'checker'] : ['light', 'dark', 'checker'] + ) + const nextBackdrop = $derived( + backdropCycle[(backdropCycle.indexOf(backdrop) + 1) % backdropCycle.length] + ) + function humanSize(n: number): string { + if (n < 1024) return `${n} B` + if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB` + return `${(n / (1024 * 1024)).toFixed(1)} MB` + } + + // A 16px checkerboard, the usual stand-in for "transparent". + const CHECKER_STYLE = + 'background-color:#ffffff;background-image:linear-gradient(45deg,#e5e7eb 25%,transparent 25%,transparent 75%,#e5e7eb 75%),linear-gradient(45deg,#e5e7eb 25%,transparent 25%,transparent 75%,#e5e7eb 75%);background-size:16px 16px;background-position:0 0,8px 8px' +</script> + +<div class="flex flex-col h-full min-h-0 bg-surface"> + <!-- The file name is the tab's label already; this bar carries what the tab cannot. --> + <div + class="flex flex-wrap items-center justify-between gap-x-2 gap-y-1 px-4 py-2 border-b border-border-light" + > + <span class="text-xs text-secondary whitespace-nowrap tabular-nums" title={name}> + {#if view.natural} + {view.natural.w} × {view.natural.h}{bytes !== undefined ? ` · ${humanSize(bytes)}` : ''} + {/if} + </span> + <div class="flex flex-wrap items-center gap-1"> + <ZoomControl + scale={view.natural ? view.scale : undefined} + min={view.minScale} + max={view.maxScale} + onZoomOut={view.zoomOut} + onZoomIn={view.zoomIn} + onZoomTo={view.zoomToAnimated} + /> + <Button + unifiedSize="sm" + variant="subtle" + iconOnly + startIcon={{ icon: Maximize }} + title="Fit to panel (0)" + disabled={!view.natural} + onClick={view.fit} + /> + <Button + unifiedSize="sm" + variant={view.zoom === 1 ? 'default' : 'subtle'} + title="Actual size (1)" + disabled={!view.natural} + onClick={view.actualSize} + > + 1:1 + </Button> + <Button + unifiedSize="sm" + variant="subtle" + iconOnly + startIcon={{ icon: BACKDROPS[backdrop].icon }} + title={`${BACKDROPS[backdrop].label} background, click for ${BACKDROPS[nextBackdrop].label.toLowerCase()}`} + onClick={() => (chosenBackdrop = nextBackdrop)} + /> + <Button + unifiedSize="sm" + variant="subtle" + iconOnly + startIcon={{ icon: Download }} + title="Download" + href={src} + download={name} + /> + </div> + </div> + + <!-- The viewport takes keys and the wheel itself: zoom follows the cursor, so it has to + be the element under it. ARIA's `application` role is the one for a surface that + handles its own pointer and keys, but Svelte does not count it as interactive. --> + <!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions --> + <div + class={twMerge( + 'relative flex-1 min-h-0 overflow-hidden outline-none select-none touch-none', + backdrop === 'light' && 'bg-white', + // The dark theme's surface-secondary in either theme: the light theme holds it as `-inverse`. + backdrop === 'dark' && (isDark.val ? 'bg-surface-secondary' : 'bg-surface-secondary-inverse'), + view.pannable ? (view.panning ? 'cursor-grabbing' : 'cursor-grab') : 'cursor-default' + )} + style={backdrop === 'checker' ? CHECKER_STYLE : undefined} + {@attach view.surface} + tabindex="0" + role="application" + aria-roledescription="image viewer" + aria-label={`${name}. Plus and minus zoom, 0 fits, 1 shows actual size.`} + onkeydown={(e) => { + if (view.handleKey(e)) e.preventDefault() + }} + > + {#if failed} + <div class="absolute inset-0 flex items-center justify-center p-4"> + <span class="rounded-md bg-surface px-3 py-2 text-xs text-secondary shadow-sm"> + This file could not be displayed as an image. + </span> + </div> + {:else} + <img + {@attach view.image} + {src} + alt={name} + draggable="false" + onerror={() => (failedSrc = src)} + class={view.imageClass} + style={view.imageStyle} + /> + {/if} + </div> +</div> diff --git a/frontend/src/lib/components/common/image/ImageViewer.svelte b/frontend/src/lib/components/common/image/ImageViewer.svelte index f7b564c22d..1fe157d04a 100644 --- a/frontend/src/lib/components/common/image/ImageViewer.svelte +++ b/frontend/src/lib/components/common/image/ImageViewer.svelte @@ -1,8 +1,9 @@ <script lang="ts"> import Portal from '$lib/components/Portal.svelte' - import { Copy, Download, ExternalLink, X, ZoomIn, ZoomOut } from 'lucide-svelte' + import { Copy, Download, ExternalLink, Maximize, PanelRight, X } from 'lucide-svelte' + import ZoomControl from './ZoomControl.svelte' + import { useZoomPan } from './zoomPan.svelte' import { fade } from 'svelte/transition' - import { on } from 'svelte/events' import { sendUserToast } from '$lib/toast' import Button from '../button/Button.svelte' import Disposable from '../drawer/Disposable.svelte' @@ -15,41 +16,23 @@ * ends in an extension (an S3 key, an attachment's file name). */ title?: string isOpen: boolean + /** Shows the image in a viewer elsewhere (a session's preview panel), closing this one. */ + onOpenInPreview?: () => void } - let { src, alt = '', title, isOpen = $bindable() }: Props = $props() + let { src, alt = '', title, isOpen = $bindable(), onOpenInPreview }: Props = $props() const caption = $derived(title || alt || 'Image') - const ZOOM_STEPS = [0.1, 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 6, 8] - const MAX_SCALE = 8 - // Room kept around a fitted image: the top bar overlays the stage, so the image clears it. - const FIT_MARGIN_X = 48 - const FIT_MARGIN_Y = 128 + /** A plain click beside the image dismisses; one that ends a pan does not. */ + let dismissOnClick = false + const view = useZoomPan({ + // The top bar overlays the stage, so a fitted image keeps clear of it. + margin: { x: 48, y: 128 }, + onTap: (onImage) => (dismissOnClick = !onImage) + }) - let natural = $state<{ w: number; h: number } | undefined>(undefined) - let stageW = $state(0) - let stageH = $state(0) - let stage: HTMLDivElement | undefined = $state(undefined) let imgEl: HTMLImageElement | undefined = $state(undefined) - - /** `fit` follows the viewport as it resizes; a number is a fixed scale of the natural size. */ - let zoom: number | 'fit' = $state('fit') - let pan = $state({ x: 0, y: 0 }) - /** Eases button and keyboard zooms; wheel and drag must track the pointer without lag. */ - let animate = $state(false) - - const fitScale = $derived( - natural && stageW && stageH - ? Math.min(1, (stageW - FIT_MARGIN_X) / natural.w, (stageH - FIT_MARGIN_Y) / natural.h) - : 1 - ) - const scale = $derived(zoom === 'fit' ? fitScale : zoom) - const minScale = $derived(Math.min(fitScale, ZOOM_STEPS[0])) - const pannable = $derived( - !!natural && (natural.w * scale > stageW + 1 || natural.h * scale > stageH + 1) - ) - let disposable: Disposable | undefined = $state(undefined) const hostActive = overlayHostActive() const shown = overlayShown() @@ -59,123 +42,13 @@ // A bound `open` alone does not put the viewer on the disposable stack, and the stack // lifts it above the drawer or dialog it was opened from and gives Escape to the topmost. disposable?.openDrawer() - zoom = 'fit' - pan = { x: 0, y: 0 } - animate = false + view.reset() } function close() { isOpen = false } - function clampPan(p: { x: number; y: number }, s: number) { - if (!natural) return { x: 0, y: 0 } - const maxX = Math.max(0, (natural.w * s - stageW) / 2) - const maxY = Math.max(0, (natural.h * s - stageH) / 2) - return { - x: Math.min(maxX, Math.max(-maxX, p.x)), - y: Math.min(maxY, Math.max(-maxY, p.y)) - } - } - - /** `at` is relative to the stage centre; that point stays under the pointer while zooming. */ - function zoomTo(next: number, at = { x: 0, y: 0 }) { - const s = Math.min(MAX_SCALE, Math.max(minScale, next)) - const k = s / scale - pan = clampPan({ x: at.x - (at.x - pan.x) * k, y: at.y - (at.y - pan.y) * k }, s) - zoom = s - } - - function fit() { - animate = true - zoom = 'fit' - pan = { x: 0, y: 0 } - } - - function zoomIn() { - animate = true - zoomTo(ZOOM_STEPS.find((z) => z > scale * 1.01) ?? MAX_SCALE) - } - - function zoomOut() { - animate = true - zoomTo(ZOOM_STEPS.findLast((z) => z < scale / 1.01) ?? minScale) - } - - function stagePoint(e: { clientX: number; clientY: number }) { - const r = stage!.getBoundingClientRect() - return { x: e.clientX - r.left - r.width / 2, y: e.clientY - r.top - r.height / 2 } - } - - function toggleZoom(e: MouseEvent) { - // The stage captures the pointer, so the double click targets the stage, not the image. - const r = imgEl?.getBoundingClientRect() - if ( - !r || - e.clientX < r.left || - e.clientX > r.right || - e.clientY < r.top || - e.clientY > r.bottom - ) - return - animate = true - if (zoom === 'fit' || Math.abs(scale - fitScale) < 0.001) { - zoomTo(fitScale < 1 ? 1 : 2, stagePoint(e)) - } else { - fit() - } - } - - function wheelZoom(node: HTMLElement) { - // Registered by hand: the default must be prevented, so the listener cannot be passive. - return on( - node, - 'wheel', - (e: WheelEvent) => { - e.preventDefault() - animate = false - const lines = e.deltaMode === 1 ? 33 : 1 - // Pinch on a trackpad arrives as ctrl+wheel with small deltas. - const speed = e.ctrlKey ? 0.01 : 0.0015 - zoomTo(scale * Math.exp(-e.deltaY * lines * speed), stagePoint(e)) - }, - { passive: false } - ) - } - - let panning = $state(false) - let drag: - | { x: number; y: number; pan: { x: number; y: number }; moved: boolean; onImage: boolean } - | undefined - - function onPointerDown(e: PointerEvent) { - if (e.button !== 0) return - drag = { x: e.clientX, y: e.clientY, pan, moved: false, onImage: e.target === imgEl } - stage?.setPointerCapture(e.pointerId) - } - - function onPointerMove(e: PointerEvent) { - if (!drag) return - const dx = e.clientX - drag.x - const dy = e.clientY - drag.y - if (!drag.moved && Math.hypot(dx, dy) < 4) return - drag.moved = true - if (pannable) { - panning = true - animate = false - pan = clampPan({ x: drag.pan.x + dx, y: drag.pan.y + dy }, scale) - } - } - - /** A plain click beside the image dismisses; one that ends a pan does not. */ - let dismissOnClick = false - - function onPointerUp() { - dismissOnClick = !!drag && !drag.moved && !drag.onImage - drag = undefined - panning = false - } - function onStageClick() { // Closed on `click`, not `pointerup`: outside-click guards elsewhere (the chat composer) // listen for this click and must still see the viewer open when it arrives. @@ -185,20 +58,7 @@ function onKeyDown(e: KeyboardEvent) { if (!isOpen || !hostActive() || !(disposable?.isTopmost() ?? true)) return - if (e.metaKey || e.ctrlKey || e.altKey) return - const action = { - '+': zoomIn, - '=': zoomIn, - '-': zoomOut, - '0': fit, - '1': () => { - animate = true - zoomTo(1) - } - }[e.key] - if (!action) return - e.preventDefault() - action() + if (view.handleKey(e)) e.preventDefault() } const MIME_EXT: Record<string, string> = { @@ -246,8 +106,11 @@ return } // Browsers refuse to open a data: URL as a page; a blob URL of the same bytes opens. + // The blob URL takes this page's origin, so only plain raster types open as they are; + // anything else, SVG included since it opens as a document, is re-encoded to PNG. try { - const url = URL.createObjectURL(await fetchBlob()) + const blob = await fetchBlob() + const url = URL.createObjectURL(RASTER_TYPES.has(blob.type) ? blob : await rasterize()) window.open(url, '_blank', 'noopener') setTimeout(() => URL.revokeObjectURL(url), 60_000) } catch (e) { @@ -255,16 +118,30 @@ } } + const RASTER_TYPES = new Set([ + 'image/png', + 'image/jpeg', + 'image/gif', + 'image/webp', + 'image/avif', + 'image/bmp' + ]) + + /** The displayed image as PNG bytes, drawn through a canvas. */ + function rasterize(): Promise<Blob> { + const canvas = document.createElement('canvas') + canvas.width = view.natural?.w ?? imgEl!.naturalWidth + canvas.height = view.natural?.h ?? imgEl!.naturalHeight + canvas.getContext('2d')!.drawImage(imgEl!, 0, 0, canvas.width, canvas.height) + return new Promise<Blob>((resolve, reject) => + canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('encoding failed'))), 'image/png') + ) + } + async function copyImage() { try { // The clipboard takes PNG in every browser, other types in few: re-encode through a canvas. - const canvas = document.createElement('canvas') - canvas.width = imgEl!.naturalWidth - canvas.height = imgEl!.naturalHeight - canvas.getContext('2d')!.drawImage(imgEl!, 0, 0) - const blob = new Promise<Blob>((resolve, reject) => - canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('encoding failed'))), 'image/png') - ) + const blob = rasterize() // Handed over as a promise so `write` runs within the click: Safari refuses it once // the user gesture has expired, which an awaited encode would let happen. await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]) @@ -296,39 +173,21 @@ transition:fade|local={{ duration: 150 }} > <div - bind:this={stage} - bind:clientWidth={stageW} - bind:clientHeight={stageH} - {@attach wheelZoom} + {@attach view.surface} class="absolute inset-0 overflow-hidden touch-none select-none" - class:cursor-grab={pannable && !panning} - class:cursor-grabbing={panning} + class:cursor-grab={view.pannable && !view.panning} + class:cursor-grabbing={view.panning} role="presentation" - onpointerdown={onPointerDown} - onpointermove={onPointerMove} - onpointerup={onPointerUp} onclick={onStageClick} - onpointercancel={() => { - drag = undefined - panning = false - }} - ondblclick={toggleZoom} > <img bind:this={imgEl} + {@attach view.image} {src} {alt} draggable="false" - class="absolute left-1/2 top-1/2 max-w-none {natural ? '' : 'opacity-0'} {animate - ? 'transition-transform duration-150 ease-out' - : ''}" - style="width: {natural?.w ?? 0}px; height: {natural?.h ?? - 0}px; transform: translate(-50%, -50%) translate({pan.x}px, {pan.y}px) scale({scale});" - onload={(e) => { - const el = e.currentTarget as HTMLImageElement - // An SVG without width/height has no intrinsic size. - natural = { w: el.naturalWidth || 1024, h: el.naturalHeight || 768 } - }} + class={view.imageClass} + style={view.imageStyle} /> </div> @@ -336,44 +195,35 @@ class="absolute inset-x-0 top-0 flex items-center justify-between gap-3 p-3 pointer-events-none" > <div - class="flex items-baseline gap-2 min-w-0 h-9 px-3 leading-9 rounded-md bg-surface-tertiary shadow-lg pointer-events-auto" + class="flex items-baseline gap-2 min-w-0 h-9 px-1 leading-9 drop-shadow pointer-events-auto" > - <span class="truncate text-xs font-semibold text-emphasis">{caption}</span> - {#if natural} - <span class="shrink-0 text-2xs text-secondary tabular-nums"> - {natural.w} × {natural.h} + <!-- The overlay is black in both themes, and a zoomed image can pass under the + caption, hence fixed white text with a shadow rather than theme tokens. --> + <span class="truncate text-xs font-medium text-white/90">{caption}</span> + {#if view.natural} + <span class="shrink-0 text-2xs text-white/60 tabular-nums"> + {view.natural.w} × {view.natural.h} </span> {/if} </div> <div class="flex shrink-0 items-center gap-0.5 h-9 px-1 rounded-md bg-surface-tertiary shadow-lg pointer-events-auto" > - <Button - variant="subtle" - unifiedSize="sm" - iconOnly - startIcon={{ icon: ZoomOut }} - title="Zoom out (−)" - disabled={scale <= minScale + 0.001} - onclick={zoomOut} + <ZoomControl + scale={view.scale} + min={view.minScale} + max={view.maxScale} + onZoomOut={view.zoomOut} + onZoomIn={view.zoomIn} + onZoomTo={view.zoomToAnimated} /> - <Button - variant="subtle" - unifiedSize="sm" - btnClasses="w-14 justify-center tabular-nums" - title="Fit to screen (0)" - onclick={fit} - > - {Math.round(scale * 100)}% - </Button> <Button variant="subtle" unifiedSize="sm" iconOnly - startIcon={{ icon: ZoomIn }} - title="Zoom in (+)" - disabled={scale >= MAX_SCALE - 0.001} - onclick={zoomIn} + startIcon={{ icon: Maximize }} + title="Fit to screen (0)" + onclick={view.fit} /> <div class="w-px h-4 mx-1 bg-border-light"></div> <Button @@ -400,6 +250,19 @@ title="Open in new tab" onclick={openInNewTab} /> + {#if onOpenInPreview} + <Button + variant="subtle" + unifiedSize="sm" + iconOnly + startIcon={{ icon: PanelRight }} + title="Open in preview" + onclick={() => { + close() + onOpenInPreview?.() + }} + /> + {/if} <div class="w-px h-4 mx-1 bg-border-light"></div> <Button variant="subtle" diff --git a/frontend/src/lib/components/common/image/ZoomControl.svelte b/frontend/src/lib/components/common/image/ZoomControl.svelte new file mode 100644 index 0000000000..fd1e44c2de --- /dev/null +++ b/frontend/src/lib/components/common/image/ZoomControl.svelte @@ -0,0 +1,97 @@ +<script lang="ts"> + import { Minus, Plus } from 'lucide-svelte' + import { Button } from '$lib/components/common' + import TextInput from '$lib/components/text_input/TextInput.svelte' + + interface Props { + /** Current scale, 1 is actual size; undefined while there is no image. */ + scale: number | undefined + min: number + max: number + onZoomOut: () => void + onZoomIn: () => void + /** A scale typed by the user, already clamped to `min`..`max`. */ + onZoomTo: (scale: number) => void + } + + let { scale, min, max, onZoomOut, onZoomIn, onZoomTo }: Props = $props() + + const percent = $derived(scale === undefined ? '' : `${Math.round(scale * 100)}%`) + let draft = $state<string | undefined>(undefined) + + function edit() { + if (scale !== undefined) draft = String(Math.round(scale * 100)) + } + + function commit() { + if (draft === undefined) return + const typed = parseFloat(draft.replace('%', '').trim()) + draft = undefined + if (Number.isFinite(typed) && typed > 0) { + onZoomTo(Math.min(max, Math.max(min, typed / 100))) + } + } + + function onKeyDown(e: KeyboardEvent) { + // The viewers bind +, -, 0 and 1 as zoom shortcuts; typed digits must not reach them. + e.stopPropagation() + if (e.key === 'Enter') commit() + else if (e.key === 'Escape') { + e.preventDefault() + draft = undefined + } + } + + function focusAndSelect(node: HTMLElement) { + const input = node.querySelector('input') + input?.focus() + input?.select() + } +</script> + +<div class="flex items-center gap-0.5"> + {#if draft !== undefined} + <div class="w-14" {@attach focusAndSelect}> + <TextInput + size="sm" + bind:value={draft} + class="text-center tabular-nums" + inputProps={{ + 'aria-label': 'Zoom level in percent', + inputmode: 'decimal', + onkeydown: onKeyDown, + onblur: commit + }} + /> + </div> + {:else} + <Button + unifiedSize="sm" + variant="subtle" + btnClasses="w-14 justify-center tabular-nums" + title="Set zoom level" + disabled={scale === undefined} + onClick={edit} + > + {percent} + </Button> + {/if} + <Button + unifiedSize="sm" + variant="subtle" + iconOnly + startIcon={{ icon: Minus }} + title="Zoom out (-)" + disabled={scale === undefined || scale <= min + 1e-3} + onClick={onZoomOut} + /> + <Button + unifiedSize="sm" + variant="subtle" + iconOnly + startIcon={{ icon: Plus }} + title="Zoom in (+)" + disabled={scale === undefined || scale >= max - 1e-3} + onClick={onZoomIn} + /> +</div> diff --git a/frontend/src/lib/components/common/image/imageOpener.ts b/frontend/src/lib/components/common/image/imageOpener.ts new file mode 100644 index 0000000000..62264703c1 --- /dev/null +++ b/frontend/src/lib/components/common/image/imageOpener.ts @@ -0,0 +1,17 @@ +import { getContext, setContext } from 'svelte' +import type { ImageSource } from '$lib/components/sessions/previewRouter' + +/** Opens an image in a viewer beside the current surface: a session's preview panel. */ +export type ImageOpener = (source: ImageSource, label: string) => void + +const KEY = 'imageOpener' + +/** Provided by a session for everything it renders, the chat and the preview tabs. */ +export function setImageOpener(opener: ImageOpener): void { + setContext(KEY, opener) +} + +/** Undefined outside a session: an image then expands in place. */ +export function getImageOpener(): ImageOpener | undefined { + return getContext<ImageOpener | undefined>(KEY) +} diff --git a/frontend/src/lib/components/common/image/zoomPan.svelte.ts b/frontend/src/lib/components/common/image/zoomPan.svelte.ts new file mode 100644 index 0000000000..38e138bd40 --- /dev/null +++ b/frontend/src/lib/components/common/image/zoomPan.svelte.ts @@ -0,0 +1,244 @@ +import { on } from 'svelte/events' + +/** The scales the zoom buttons and keys step between; the wheel zooms continuously. */ +const ZOOM_STEPS = [0.1, 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 6, 8, 12, 16, 24, 32] +const MAX_SCALE = 32 +// From this scale up, pixels are drawn as hard squares: smoothing an upscaled +// screenshot or icon blurs exactly the detail the user zoomed in to look at. +const PIXELATED_FROM = 2 + +type Point = { x: number; y: number } + +/** + * Zoom and pan of one image inside a surface: fit, zoom around a point, step, wheel, + * drag, double-click and the `+` `-` `0` `1` keys. Attach `surface` to the element that + * clips the image and `image` to the `<img>`, which `imageStyle` positions at the + * surface's centre. + */ +export function useZoomPan(opts: { + /** Room kept around a fitted image, in total per axis. */ + margin: Point + /** A click that did not drag; `onImage` tells whether it landed on the image. */ + onTap?: (onImage: boolean) => void +}) { + let natural = $state<{ w: number; h: number } | undefined>(undefined) + let viewW = $state(0) + let viewH = $state(0) + /** `fit` follows the surface as it resizes; a number is a fixed scale of the natural size. */ + let zoom = $state<number | 'fit'>('fit') + let pan = $state<Point>({ x: 0, y: 0 }) + /** Eases button and keyboard zooms; wheel and drag must track the pointer without lag. */ + let animate = $state(false) + let panning = $state(false) + let surfaceEl: HTMLElement | undefined + let imageEl: HTMLImageElement | undefined + + // Fit never enlarges: a small image is shown at its real size rather than blown up. + const fitScale = $derived( + natural && viewW > 0 && viewH > 0 + ? Math.min( + 1, + Math.max(viewW - opts.margin.x, 1) / natural.w, + Math.max(viewH - opts.margin.y, 1) / natural.h + ) + : 1 + ) + const scale = $derived(zoom === 'fit' ? fitScale : zoom) + const minScale = $derived(Math.min(fitScale, ZOOM_STEPS[0])) + const pannable = $derived( + !!natural && (natural.w * scale > viewW + 1 || natural.h * scale > viewH + 1) + ) + + function clampPan(p: Point, s: number): Point { + if (!natural) return { x: 0, y: 0 } + const maxX = Math.max(0, (natural.w * s - viewW) / 2) + const maxY = Math.max(0, (natural.h * s - viewH) / 2) + return { + x: Math.min(maxX, Math.max(-maxX, p.x)), + y: Math.min(maxY, Math.max(-maxY, p.y)) + } + } + + /** `at` is relative to the surface's centre; the image point there stays put. */ + function zoomTo(next: number, at: Point = { x: 0, y: 0 }) { + const s = Math.min(MAX_SCALE, Math.max(minScale, next)) + const k = s / scale + pan = clampPan({ x: at.x - (at.x - pan.x) * k, y: at.y - (at.y - pan.y) * k }, s) + zoom = s + } + + function fit() { + animate = true + zoom = 'fit' + pan = { x: 0, y: 0 } + } + + function zoomIn() { + animate = true + zoomTo(ZOOM_STEPS.find((z) => z > scale * 1.01) ?? MAX_SCALE) + } + + function zoomOut() { + animate = true + zoomTo(ZOOM_STEPS.findLast((z) => z < scale / 1.01) ?? minScale) + } + + function actualSize() { + animate = true + zoomTo(1) + } + + function surfacePoint(e: { clientX: number; clientY: number }): Point { + const r = surfaceEl!.getBoundingClientRect() + return { x: e.clientX - r.left - r.width / 2, y: e.clientY - r.top - r.height / 2 } + } + + let drag: { x: number; y: number; pan: Point; moved: boolean; onImage: boolean } | undefined + + function endDrag() { + drag = undefined + panning = false + } + + function surface(node: HTMLElement) { + surfaceEl = node + const resize = new ResizeObserver(() => { + viewW = node.clientWidth + viewH = node.clientHeight + }) + resize.observe(node) + const offs = [ + // Not passive: the page must not scroll under a wheel zoom. + on( + node, + 'wheel', + (e: WheelEvent) => { + if (!natural) return + e.preventDefault() + animate = false + const lines = e.deltaMode === 1 ? 33 : 1 + // Pinch on a trackpad arrives as ctrl+wheel with small deltas. + const speed = e.ctrlKey ? 0.01 : 0.0015 + zoomTo(scale * Math.exp(-e.deltaY * lines * speed), surfacePoint(e)) + }, + { passive: false } + ), + on(node, 'pointerdown', (e: PointerEvent) => { + if (e.button !== 0) return + drag = { x: e.clientX, y: e.clientY, pan, moved: false, onImage: e.target === imageEl } + node.setPointerCapture(e.pointerId) + }), + on(node, 'pointermove', (e: PointerEvent) => { + if (!drag) return + const dx = e.clientX - drag.x + const dy = e.clientY - drag.y + if (!drag.moved && Math.hypot(dx, dy) < 4) return + drag.moved = true + if (pannable) { + panning = true + animate = false + pan = clampPan({ x: drag.pan.x + dx, y: drag.pan.y + dy }, scale) + } + }), + on(node, 'pointerup', () => { + if (drag && !drag.moved) opts.onTap?.(drag.onImage) + endDrag() + }), + on(node, 'pointercancel', endDrag), + on(node, 'dblclick', (e: MouseEvent) => { + if (!natural) return + animate = true + if (zoom === 'fit' || Math.abs(scale - fitScale) < 0.001) { + zoomTo(fitScale < 1 ? 1 : 2, surfacePoint(e)) + } else { + fit() + } + }) + ] + return () => { + resize.disconnect() + offs.forEach((off) => off()) + surfaceEl = undefined + } + } + + function image(node: HTMLImageElement) { + imageEl = node + const measure = () => { + // An SVG without width/height has no intrinsic size. + natural = { w: node.naturalWidth || 1024, h: node.naturalHeight || 768 } + } + if (node.complete && node.naturalWidth) measure() + const off = on(node, 'load', measure) + return () => { + off() + imageEl = undefined + } + } + + return { + get natural() { + return natural + }, + get scale() { + return scale + }, + get minScale() { + return minScale + }, + maxScale: MAX_SCALE, + get zoom() { + return zoom + }, + get pannable() { + return pannable + }, + get panning() { + return panning + }, + /** Positions the image: its natural size, centred, then panned and scaled. */ + get imageStyle() { + return `width: ${natural?.w ?? 0}px; height: ${natural?.h ?? 0}px; transform: translate(-50%, -50%) translate(${pan.x}px, ${pan.y}px) scale(${scale});` + }, + get imageClass() { + return [ + 'absolute left-1/2 top-1/2 max-w-none', + natural ? '' : 'opacity-0', + animate ? 'transition-transform duration-150 ease-out' : '', + scale >= PIXELATED_FROM ? '[image-rendering:pixelated]' : '' + ].join(' ') + }, + surface, + image, + fit, + zoomIn, + zoomOut, + actualSize, + /** Eased, for a zoom the user typed or picked. */ + zoomToAnimated(next: number) { + animate = true + zoomTo(next) + }, + /** Back to fit with no easing, for a viewer shown afresh. */ + reset() { + zoom = 'fit' + pan = { x: 0, y: 0 } + animate = false + }, + /** Handles a zoom key; returns whether it did, so the caller can prevent its default. */ + handleKey(e: KeyboardEvent): boolean { + if (e.metaKey || e.ctrlKey || e.altKey) return false + const action = { + '+': zoomIn, + '=': zoomIn, + '-': zoomOut, + _: zoomOut, + '0': fit, + '1': actualSize + }[e.key] + if (!action) return false + action() + return true + } + } +} diff --git a/frontend/src/lib/components/copilot/FlowInlineScriptAIButton.svelte b/frontend/src/lib/components/copilot/FlowInlineScriptAIButton.svelte index b16f23bf00..25e7f079ef 100644 --- a/frontend/src/lib/components/copilot/FlowInlineScriptAIButton.svelte +++ b/frontend/src/lib/components/copilot/FlowInlineScriptAIButton.svelte @@ -1,15 +1,16 @@ <script lang="ts"> import Button from '../common/button/Button.svelte' - import { tick, type ComponentProps } from 'svelte' + import type { ComponentProps } from 'svelte' import OpenInSessionButton from '$lib/components/sessions/OpenInSessionButton.svelte' - import { getOpenInSessionHandoff } from '$lib/components/sessions/openInSessionContext' + import { + getOpenInSessionHandoff, + withEditorFlush + } from '$lib/components/sessions/openInSessionContext' interface Props { moduleId?: string - /** Materializes Monaco's in-flight keystrokes into the draft. This button - * sits in the code editor's own toolbar, so "type, then click" is the - * normal case, and the session preview loads the item from its draft — - * without this the last (sub-second) edits would not be in it. */ + /** Materializes Monaco's in-flight keystrokes into the draft: this button sits in + * the code editor's own toolbar, so "type, then click" is the normal case. */ flushEditor?: () => void btnProps?: ComponentProps<typeof Button> } @@ -21,17 +22,7 @@ const handoff = getOpenInSessionHandoff() const sessionSource = $derived.by(() => { const source = handoff?.source({ moduleId }) - if (!source || !flushEditor) return source - return { - ...source, - beforeOpen: async () => { - flushEditor() - // The flush lands in the draft store through an effect; let it run - // before the hand-off persists that store. - await tick() - await source.beforeOpen?.() - } - } + return source && flushEditor ? withEditorFlush(source, flushEditor) : source }) </script> diff --git a/frontend/src/lib/components/copilot/ScriptGen.svelte b/frontend/src/lib/components/copilot/ScriptGen.svelte index 4b141ec228..ad7acc6c3a 100644 --- a/frontend/src/lib/components/copilot/ScriptGen.svelte +++ b/frontend/src/lib/components/copilot/ScriptGen.svelte @@ -22,10 +22,14 @@ import { AlertTriangle, Ban, Check, ExternalLink, HistoryIcon, Wand2, X } from 'lucide-svelte' import { fade } from 'svelte/transition' import { isInitialCode } from '$lib/script_helpers' - import { twMerge } from 'tailwind-merge' import { onDestroy, type ComponentProps } from 'svelte' import ProviderModelSelector from './chat/ProviderModelSelector.svelte' - import { copilotInfo } from '$lib/aiStore' + import { + copilotInfo, + scriptGenModel, + setScriptGenModelPick, + tryResolveModelFor + } from '$lib/aiStore' interface Props { // props @@ -62,6 +66,7 @@ let generatedCode = writable<string>('') let dbSchema: DBSchema | undefined = $state(undefined) let abortController: AbortController | undefined = $state(undefined) + let model = $derived(tryResolveModelFor($copilotInfo, $scriptGenModel)) let blockPopupOpen = $state(false) let mode: 'gen' | 'edit' = $state('gen') @@ -71,34 +76,19 @@ trimmedDesc = funcDesc.trim() }) async function callCopilot() { - if (mode === 'edit') { - await copilot( - { - // @ts-ignore - language: transformer && lang === 'frontend' ? 'transformer' : lang!, - description: trimmedDesc, - code: editor?.getCode() || '', - dbSchema: dbSchema, - type: 'edit', - workspace: $workspaceStore! - }, - generatedCode, - abortController! - ) - } else { - await copilot( - { - // @ts-ignore - language: transformer && lang === 'frontend' ? 'transformer' : lang!, - description: trimmedDesc, - dbSchema: dbSchema, - type: 'gen', - workspace: $workspaceStore! - }, - generatedCode, - abortController! - ) - } + await copilot( + { + // @ts-ignore + language: transformer && lang === 'frontend' ? 'transformer' : lang!, + description: trimmedDesc, + dbSchema: dbSchema, + workspace: $workspaceStore!, + ...(mode === 'edit' ? { type: 'edit', code: editor?.getCode() || '' } : { type: 'gen' }) + }, + generatedCode, + abortController!, + { forceModelProvider: model } + ) } function handleAiButtonClick() { @@ -132,13 +122,13 @@ showDiff() funcDesc = '' } catch (err) { - if (!abortController?.signal.aborted) { - if (err?.message) { - sendUserToast('Failed to generate code: ' + err.message, true) - } else { - sendUserToast('Failed to generate code', true) - console.error(err) - } + if (abortController?.signal.aborted) { + clear() + } else if (err?.message) { + sendUserToast('Failed to generate code: ' + err.message, true) + } else { + sendUserToast('Failed to generate code', true) + console.error(err) } } finally { genLoading = false @@ -364,39 +354,38 @@ ] }} disabled={blockPopupOpen} + onClose={() => { + // Escape or a click on the overlay closes the box mid-request, taking its Stop with it. + if (blockPopupOpen) abortController?.abort() + }} > {#snippet trigger()} {#if inlineScript} <Button - size="xs" - color={genLoading ? 'red' : 'light'} - btnClasses={twMerge(genLoading ? '!px-3 z-[5000]' : '!px-2')} - propagateEvent={!genLoading} - on:click={genLoading ? () => abortController?.abort() : handleAiButtonClick} + unifiedSize="sm" + variant="subtle" + btnClasses="!px-2" + disabled={genLoading} + on:click={handleAiButtonClick} bind:element={button} iconOnly title="Generate code from prompt" - startIcon={genLoading ? { icon: Ban } : { icon: Wand2, classes: 'text-ai' }} + startIcon={{ icon: Wand2, classes: 'text-ai' }} {...btnProps} /> {:else} <Button title="Generate code from prompt" - btnClasses={twMerge('!font-medium', genLoading ? 'z-[5000]' : 'text-ai')} - size="xs" - color={genLoading ? 'red' : 'light'} - spacingSize="md" - startIcon={genLoading ? { icon: Ban } : { icon: Wand2 }} - propagateEvent={!genLoading} - on:click={genLoading ? () => abortController?.abort() : handleAiButtonClick} + btnClasses="!font-medium text-ai" + unifiedSize="sm" + variant="subtle" + startIcon={{ icon: Wand2 }} + disabled={genLoading} + on:click={handleAiButtonClick} bind:element={button} {...btnProps} > - {#if genLoading} - Stop - {:else} - AI Gen - {/if} + AI Gen </Button> {/if} {/snippet} @@ -412,18 +401,24 @@ <LoadingIcon /> {/if} </div> + <div class="flex justify-end pt-2"> + <Button + unifiedSize="sm" + variant="default" + startIcon={{ icon: Ban }} + onClick={() => abortController?.abort()} + > + Stop + </Button> + </div> {:else if $copilotInfo.enabled} <div class="flex flex-col gap-4"> - <div class="flex flex-row justify-between items-center w-96 gap-2"> - <ToggleButtonGroup class="w-auto shrink-0 h-auto" bind:selected={mode}> - {#snippet children({ item })} - <ToggleButton value={'gen'} label="Generate from scratch" class="px-2" {item} /> - <ToggleButton value={'edit'} label="Edit existing code" class="px-2" {item} /> - {/snippet} - </ToggleButtonGroup> - - <ProviderModelSelector /> - </div> + <ToggleButtonGroup class="w-auto self-start h-auto" bind:selected={mode}> + {#snippet children({ item })} + <ToggleButton value={'gen'} label="Generate from scratch" class="px-2" {item} /> + <ToggleButton value={'edit'} label="Edit existing code" class="px-2" {item} /> + {/snippet} + </ToggleButtonGroup> <div class="flex w-96 items-start"> <textarea bind:this={input} @@ -456,6 +451,9 @@ startIcon={{ icon: Wand2 }} /> </div> + <div class="flex w-96 justify-end items-center gap-1 -mt-3"> + <ProviderModelSelector {model} onPick={setScriptGenModelPick} /> + </div> {#if promptHistory.length > 0} <div class="w-96 flex flex-col gap-1"> {#each promptHistory as p} diff --git a/frontend/src/lib/components/copilot/StepInputsGen.svelte b/frontend/src/lib/components/copilot/StepInputsGen.svelte index eb227713a2..b9ceb6be66 100644 --- a/frontend/src/lib/components/copilot/StepInputsGen.svelte +++ b/frontend/src/lib/components/copilot/StepInputsGen.svelte @@ -264,7 +264,7 @@ input_name2: expression2 {:else} Enable step input completion in the{' '} <a - href="#user-settings" + href="#user-settings-ai" class="inline-flex flex-row items-center gap-1" onclick={(e) => { if (!isNewTabClick(e)) close() diff --git a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte index fa6d809aa4..697b42f01b 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte @@ -523,7 +523,7 @@ return } // Otherwise (folders / multi-select): summarize to avoid a flood of toasts. The only - // per-file rejection left is non-text content (binary files are skipped). + // per-file rejection left is binary content other than images. const lead = added.length ? `Attached ${added.length}, skipped ${rejected.length}` : `Skipped ${rejected.length} file${rejected.length === 1 ? '' : 's'}` @@ -663,10 +663,9 @@ const entries = await readDroppedEntries(Array.from(dt.items ?? [])) const source: FileToAttach[] = entries.length > 0 ? entries : flatFiles // Top-level files attach to the message (images were already reserved - // from dt.files before the walk). Folder children keep riding the - // session store as a snapshot — including nested images, which are - // deliberately NOT attached (the FSA path never extracts folder - // contents either); they are summarized as skipped there. + // from dt.files before the walk). Folder children ride the session store + // as a snapshot, nested images included: they become image rows the + // preview can show, never message attachments, as on the FSA path. const topLevelText: File[] = [] const folderEntries: FileToAttach[] = [] for (const entry of source) { diff --git a/frontend/src/lib/components/copilot/chat/AIChatInlineWidget.svelte b/frontend/src/lib/components/copilot/chat/AIChatInlineWidget.svelte index da1a1e26af..73ddcf1e28 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatInlineWidget.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatInlineWidget.svelte @@ -1,239 +1,74 @@ <script lang="ts"> import * as monaco from 'monaco-editor' - import AIChatInput from './AIChatInput.svelte' - import { aiChatManager, AIMode } from './AIChatManager.svelte' - import type { Selection } from 'monaco-editor' - import ChatTypingIndicator from './ChatTypingIndicator.svelte' - import { sendUserToast } from '$lib/toast' - import { onDestroy } from 'svelte' - import type { AIChatEditorHandler } from './monaco-adapter' - import { getModifierKey } from '$lib/utils' + import { clickOutside } from '$lib/utils' + import InlinePrompt from './InlinePrompt.svelte' interface Props { editor: monaco.editor.IStandaloneCodeEditor - selection: Selection | null - selectedCode: string - show: boolean - editorHandler: AIChatEditorHandler + /** The line the box sits over. */ + line: number + /** Resolving to `false` keeps the box open with its text. */ + onSend: (prompt: string) => Promise<boolean> + /** `refocus` unless closing on a click, which already put the focus where the user wants it. */ + onClose: (refocus: boolean) => void } - let { editor, selection, selectedCode, show = $bindable(false), editorHandler }: Props = $props() + let { editor, line, onSend, onClose }: Props = $props() - let widget: AIChatWidget | null = $state(null) let widgetElement: HTMLElement | null = $state(null) - let aiChatInput: AIChatInput | null = $state(null) - let processing = $state(false) - let marginToAdd = $state(0) + let prompt: InlinePrompt | undefined = $state() - class AIChatWidget implements monaco.editor.IContentWidget { - private domNode: HTMLElement - public position: monaco.IPosition - editor: monaco.editor.IStandaloneCodeEditor - private originalPadding: number = 0 - private editorHandler: AIChatEditorHandler - - constructor( - lineNumber: number, - domNode: HTMLElement, - editor: monaco.editor.IStandaloneCodeEditor, - editorHandler: AIChatEditorHandler - ) { - this.domNode = domNode - this.position = { lineNumber, column: 0 } - this.editor = editor - this.editorHandler = editorHandler - this.ensureSpaceAbove() - - this.editor.onDidScrollChange((e) => { - this.domNode.style.visibility = 'inherit' + $effect(() => { + const domNode = widgetElement + if (!domNode) return + const widget: monaco.editor.IContentWidget = { + // Monaco's overflow layer, which draws above the buttons hosts float over the editor. + allowEditorOverflow: true, + getId: () => 'ai-inline-chat-widget', + getDomNode: () => domNode, + getPosition: () => ({ + position: { lineNumber: line, column: 1 }, + preference: [monaco.editor.ContentWidgetPositionPreference.ABOVE] }) } - - private ensureSpaceAbove() { - const widgetHeight = 100 - const additionalPadding = 15 - const linesHeight = 20 * this.position.lineNumber - if (linesHeight < widgetHeight + additionalPadding) { - // Add top margin to editor to make space - const editorDom = this.editor.getDomNode() - if (editorDom) { - const neededPadding = widgetHeight + additionalPadding - linesHeight - this.originalPadding = this.editor.getOption(monaco.editor.EditorOption.padding)?.top || 0 - this.editor.updateOptions({ - padding: { - top: neededPadding - } - }) - // Trigger layout update - this.editor.layout() - } - } - } - - private restoreEditorSpacing() { - if (this.position.lineNumber < 10) { - const editorDom = this.editor.getDomNode() - if (editorDom) { - this.editor.updateOptions({ - padding: { - top: this.originalPadding - } - }) - this.editor.layout() - } - } - } - - getId(): string { - return 'ai-inline-chat-widget' - } - - getDomNode(): HTMLElement { - return this.domNode - } - - getAddedLines(): number { - if (!this.editorHandler || !this.editorHandler.groupChanges) { - return 0 - } - - let totalAddedLines = 0 - let totalRemovedLines = 0 - for (const group of this.editorHandler.groupChanges) { - for (const change of group.changes) { - if (change.type === 'added_block') { - // Count newlines in the added content - const lines = change.value.split('\n').length - 1 - totalAddedLines += Math.max(1, lines) - } else if (change.type === 'deleted') { - const lines = change.range.endLine - change.range.startLine + 1 - totalRemovedLines += Math.max(1, lines) - } - } - } - return totalAddedLines - totalRemovedLines - } - - getPosition(): monaco.editor.IContentWidgetPosition { - return { - position: this.position, - preference: [monaco.editor.ContentWidgetPositionPreference.ABOVE] - } - } - - dispose() { - this.restoreEditorSpacing() - } - } - - // Cleanup function to safely remove widget and cancel inline requests - function cleanupWidget(reason?: string) { - aiChatManager.cancelInlineRequest(reason ?? 'aiChatInlineWidget destroyed') - if (widget) { - try { - widget.dispose() - editor.removeContentWidget(widget) - } catch (error) { - console.warn('Failed to remove content widget:', error) - } - widget = null - } - } - - // Create/remove widget based on show state - $effect(() => { - if (show && !widget && widgetElement && selection) { - if (aiChatManager.mode !== AIMode.SCRIPT) { - aiChatManager.changeMode(AIMode.SCRIPT) - } - const startLine = selection.startLineNumber - widget = new AIChatWidget(startLine, widgetElement, editor, editorHandler) - editor.addContentWidget(widget) - if (aiChatInput) { - aiChatInput.focusInput() - } - } else if (!show && widget) { - cleanupWidget('aiChatInlineWidget hidden') - } - }) - - onDestroy(() => { - cleanupWidget('aiChatInlineWidget destroyed') - }) - - export function focusInput() { - setTimeout(() => { - aiChatInput?.focusInput() - }, 130) - } - - // Reactive effect to update margin when review state changes - $effect(() => { - const isInReviewMode = aiChatManager.pendingNewCode !== undefined - - if (isInReviewMode && widget) { - const addedLines = widget.getAddedLines() - if (widgetElement) { - marginToAdd = addedLines * 25 - widgetElement.style.marginTop = `-${marginToAdd}px` - } - } else { - marginToAdd = 0 + const padding = editor.getOption(monaco.editor.EditorOption.padding).top + // Monaco cuts off a widget taller than what is above its line. + const room = domNode.offsetHeight + 16 + const missing = room - editor.getTopForLineNumber(line) + if (missing > 0) editor.updateOptions({ padding: { top: padding + missing } }) + // Nor does it draw one whose line is out of view. + const top = editor.getTopForLineNumber(line) + const bottom = top + editor.getOption(monaco.editor.EditorOption.lineHeight) + const lowest = bottom - editor.getLayoutInfo().height + editor.setScrollTop(Math.min(Math.max(editor.getScrollTop(), lowest), top - room)) + editor.addContentWidget(widget) + // That layer is not cut at the editor's edge: scrolled up, the box would cover its toolbar. + const scroll = editor.onDidScrollChange(() => { + const above = editor.getTopForLineNumber(line) - editor.getScrollTop() + const hidden = above < domNode.offsetHeight + domNode.classList.toggle('opacity-0', hidden) + domNode.classList.toggle('pointer-events-none', hidden) + }) + // Monaco places the widget, and takes its focus with it, on its next render. + const timeout = setTimeout(() => prompt?.focus(), 130) + return () => { + clearTimeout(timeout) + scroll.dispose() + editor.updateOptions({ padding: { top: padding } }) + editor.removeContentWidget(widget) } }) </script> -{#snippet pendingApplyHint()} - <span class="text-xs text-primary pr-1"> - {getModifierKey()}↓ to apply - </span> -{/snippet} - -{#if show} - <div bind:this={widgetElement} class="w-[300px] -mt-2 relative"> - {#if processing} - <div class="absolute -top-5 left-2 pointer-events-none z-10"> - <ChatTypingIndicator loading={processing} compact /> - </div> - {/if} - <AIChatInput - bind:this={aiChatInput} - availableContext={aiChatManager.contextManager.getAvailableContext()} - selectedContext={aiChatManager.contextManager.getSelectedContext()} - onClickOutside={() => { - show = false - }} - onSendRequest={async (instructions) => { - if (!selection || processing) { - return - } - - processing = true - - try { - const reply = await aiChatManager.sendInlineRequest(instructions, selectedCode, selection) - if (reply) { - await aiChatManager.applyScriptEditorCode(reply) - } - } catch (error) { - console.error('Inline AI request failed:', error) - if (error instanceof Error) { - sendUserToast('AI request failed: ' + error.message, true) - } else { - sendUserToast('AI request failed: Unknown error', true) - } - } finally { - processing = false - } - - focusInput() - }} - showContext={false} - className="-ml-2" - bottomRightSnippet={aiChatManager.pendingNewCode ? pendingApplyHint : undefined} - loading={processing} - onCancel={() => aiChatManager.cancelInlineRequest('user pressed stop')} - disabled={processing} - /> - </div> -{/if} +<div + bind:this={widgetElement} + class="w-[300px] -mt-2 z-20" + use:clickOutside={{ onClickOutside: () => onClose(false) }} +> + <InlinePrompt + bind:this={prompt} + ariaLabel="Prompt about the selected code" + {onSend} + onClose={() => onClose(true)} + /> +</div> diff --git a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte index fa2d676590..a38a63cb15 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte @@ -7,8 +7,8 @@ contextElementKey, createAttachedFileContextElement, isMentionContext, + isPickContext, isSameContextElement, - type AppDomSelectorElement, type ContextElement } from './context' import { AIMode } from './AIChatManager.svelte' @@ -85,19 +85,10 @@ onEditEnd?: () => void className?: string onClickOutside?: () => void - 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 - // (e.g. the inline ⌘K widget runs requests outside the global - // `chatHost.loading` flag). - loading?: boolean - // Called when the user clicks Stop. Defaults to `chatHost.cancel()`. - onCancel?: () => void // Observe the composer draft as it changes (the text is local state — // `chatHost.instructions` only carries programmatic prompts). Used by // sessions to persist the typed-but-unsent prompt with the session draft. @@ -144,13 +135,9 @@ onEditEnd = () => {}, className = '', onClickOutside = () => {}, - onSendRequest = undefined, showContext = true, - bottomRightSnippet, clearHint = false, onKeyDown = undefined, - loading, - onCancel, onDraftChange = undefined, initialAttachments = undefined, onAttachmentsChange = undefined, @@ -637,9 +624,7 @@ chatHost.mode === AIMode.GLOBAL ) - const domSelectorChips = $derived( - (selectedContext ?? []).filter((c): c is AppDomSelectorElement => c.type === 'app_dom_selector') - ) + const pickChips = $derived((selectedContext ?? []).filter(isPickContext)) const contextKey = contextElementKey @@ -984,6 +969,12 @@ chatManager.contextManager?.consumeMentionContext() } + /** Apart from the mentions, which an answer to a question consumes too: it carries no pick. */ + function consumePicksIfGlobal() { + if (chatHost.mode !== AIMode.GLOBAL) return + chatManager.contextManager?.consumePickContext() + } + /** `midTurn`: Ctrl/⌘+Enter, which sends a message queued behind a running turn into that * turn instead of after it (`ChatViewHost.sendQueuedMidTurn`). */ function sendRequest({ midTurn = false }: { midTurn?: boolean } = {}) { @@ -1036,6 +1027,7 @@ ) // Consumed at enqueue, not at flush: the entry above pinned them. consumeMentionsIfGlobal() + consumePicksIfGlobal() contextTextareaComponent?.clearForSend() } // With an empty composer, this marks what is already queued. @@ -1063,6 +1055,7 @@ // when given no override, and the consume below empties it. const carried = chatHost.mode === AIMode.GLOBAL ? [...selectedContext] : undefined consumeMentionsIfGlobal() + consumePicksIfGlobal() // A host that refuses the turn puts the draft back itself (see AIChatManager's // restoreToInput and FlowChatViewHost's upload failure): restoring here too // would double the text and every attachment. @@ -1072,8 +1065,7 @@ images: sent.images, files: sent.files, blobs: sent.blobs, - contextOverride: carried, - contextOverrideOrigin: carried ? 'pinned' : undefined + contextOverride: carried }) // clearForSend() pre-zaps the textarea's mention-sync so the wipe doesn't // drop `selectedContext` before the send has settled its context: the pin @@ -1086,9 +1078,6 @@ } } - // A custom `onSendRequest` consumer (e.g. the inline ⌘K widget) has no chip - // display, so it gets the fully expanded text; the default path keeps tokens - // for the conversation bubble and expands them for the LLM inside the manager. /** Enter in a plain textarea. Ctrl/⌘ sends without stopping, and that press stops here for * the same reason as in `ContextTextarea`: pages bind their own Ctrl/⌘+Enter on the window. */ function sendFromEnter(e: KeyboardEvent) { @@ -1098,14 +1087,6 @@ sendRequest({ midTurn }) } - function submitRequest(options: { midTurn?: boolean } = {}) { - if (onSendRequest) { - onSendRequest(expanded(chatDraft(draft.text, draft.pastes))) - } else { - sendRequest(options) - } - } - $effect(() => { if (editingMessageIndex !== null) { focusInput() @@ -1342,12 +1323,11 @@ <!-- The turn stays `loading` while parked on a question, but a drafted answer is what the button should ship then — otherwise the only pointer action on a typed answer would be Stop. Anything else keeps Stop. --> - {@const isLoading = (loading ?? chatHost.loading) && !questionAnsweredBySend} + {@const isLoading = chatHost.loading && !questionAnsweredBySend} {@const emptyDraft = draft.isEmpty} <!-- A text-free GLOBAL draft with context chips is a valid turn (Enter already sends it), so the button stays enabled there for pointer/touch - parity — mirrors the sendRequest guard. Custom onSendRequest consumers - (inline ⌘K) and editor copilots need content. --> + parity — mirrors the sendRequest guard. Editor copilots need content. --> {@const needsText = chatHost.requiresMessageText && draft.text.trim() === ''} <!-- The wording is about the attachment, so it earns its place only once there is one: an empty composer is the idle state, not a refusal. --> @@ -1359,10 +1339,7 @@ pendingBlobs > 0 || ingestionHolds > 0 || needsText || - (emptyDraft && - (onSendRequest !== undefined || - chatHost.mode !== AIMode.GLOBAL || - selectedContext.length === 0))} + (emptyDraft && (chatHost.mode !== AIMode.GLOBAL || 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. --> <div class="relative flex shrink-0"> @@ -1389,9 +1366,9 @@ disabled={!isLoading && sendDisabled} on:click={() => { if (isLoading) { - onCancel ? onCancel() : chatHost.cancel() + chatHost.cancel() } else if (!sendDisabled) { - submitRequest() + sendRequest() } }} /> @@ -1399,11 +1376,11 @@ {/snippet} <!-- One wrapping row for every badge-shaped chip: selected context (or, when the - picker row is hidden — showContext=false in GLOBAL/session mode — the raw-app - inspector's DOM picks, which always show), then message files. Only image + picker row is hidden — showContext=false in GLOBAL/session mode — the preview elements + and code the user picked, which always show), then message files. Only image thumbnails get their own row (different height). --> {#snippet badgeRow()} - {@const contextChips = showContext ? selectedContext : domSelectorChips} + {@const contextChips = showContext ? selectedContext : pickChips} {#if contextChips.length > 0 || draft.files.length > 0 || pendingFiles > 0 || draft.blobs.length > 0 || pendingBlobs > 0} <div class="flex flex-row flex-wrap items-center gap-1 px-2.5 pt-2"> {#each contextChips as element (contextKey(element))} @@ -1502,7 +1479,6 @@ !e.defaultPrevented && e.target instanceof HTMLTextAreaElement && editingMessageIndex === null && - onSendRequest === undefined && draft.isEmpty && pendingImages === 0 && pendingFiles === 0 && @@ -1515,9 +1491,8 @@ // Empty means no attachment still decoding/reading either — // recalling over an attachments-only draft would clobber it. // Textarea only — ArrowUp on the wrapper's buttons/badges must not - // mutate the composer; and main composer only — the edit input and - // custom-send consumers (inline widget) have their own history - // semantics. + // mutate the composer; and main composer only — the edit input has + // its own history semantics. if ( chatHost.queuedMessage || chatHost.queuedImages.length > 0 || @@ -1564,7 +1539,7 @@ if (disabled) { return } - submitRequest({ midTurn: withModifier }) + sendRequest({ midTurn: withModifier }) }} {disabled} {onKeyDown} @@ -1582,7 +1557,7 @@ {@render toolbarRow()} {/snippet} </ContextTextarea> - {#if !bottomRightSnippet && !toolbarInBox} + {#if !toolbarInBox} <div class="absolute bottom-1 right-1"> {@render sendStopButton()} </div> @@ -1623,11 +1598,9 @@ class={twMerge('resize-none', CHAT_INPUT_PADDING)} {disabled} ></textarea> - {#if !bottomRightSnippet} - <div class="absolute bottom-1 right-1"> - {@render sendStopButton()} - </div> - {/if} + <div class="absolute bottom-1 right-1"> + {@render sendStopButton()} + </div> </div> {#if showAppContextTooltip} <Portal target="body"> @@ -1681,20 +1654,13 @@ class={twMerge('resize-none', COMPOSER_FIELD_RESET, CHAT_INPUT_PADDING)} {disabled} ></textarea> - {#if !bottomRightSnippet} - <div class="absolute bottom-1 right-1"> - {@render sendStopButton()} - </div> - {/if} + <div class="absolute bottom-1 right-1"> + {@render sendStopButton()} + </div> </div> </div> {/if} {#if toolbar && !toolbarInBox} <div class="mt-1">{@render toolbar()}</div> {/if} - {#if bottomRightSnippet} - <div class="absolute bottom-1 right-1"> - {@render bottomRightSnippet()} - </div> - {/if} </div> diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts index ba5ba27815..0c07149479 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts @@ -47,11 +47,7 @@ import type { ChatCompletionMessageParam, ChatCompletionSystemMessageParam } from 'openai/resources/chat/completions.mjs' -import { - prepareInlineChatSystemPrompt, - prepareScriptSystemMessage, - prepareScriptTools -} from './script/core' +import { prepareScriptSystemMessage, prepareScriptTools } from './script/core' import type { ScriptLintResult } from './shared' import { navigatorTools, prepareNavigatorSystemMessage } from './navigator/core' import { loadApiTools } from './api/apiTools' @@ -127,11 +123,13 @@ import { createAppFrontendFileContextElement, flattenDatatablesToAppContextElements, isMentionContext, + isPickContext, isSameContextElement, + type CodeSelection, type ContextElement, + type PickContext, type AppDatatableElement } from './context' -import type { Selection } from 'monaco-editor' import type AIChatInput from './AIChatInput.svelte' import { prepareApiSystemMessage, prepareApiUserMessage } from './api/core' import { @@ -217,7 +215,11 @@ import { scopedKey, onUserChange, migrateLegacyLocalStorage } from '$lib/userSco import { getLocalSetting, storeLocalSetting } from '$lib/utils' import { AttachedFilesStore } from './files/attachedFiles.svelte' import { SessionArtifactsStore } from './artifacts/artifactsState.svelte' -import type { ArtifactVersionTarget, S3FileRef } from '$lib/components/sessions/previewRouter' +import type { + ArtifactVersionTarget, + ImageSource, + S3FileRef +} from '$lib/components/sessions/previewRouter' import { appendAttachedFilesRoster } from './files/fileTools' import { ENTER_PLAN_MODE_TOOL, EXIT_PLAN_MODE_TOOL } from './planMode' import { PlanModeController, type PlanModeHost } from './planModeController.svelte' @@ -471,7 +473,7 @@ function refreshFreeTierUsage(workspace: string | undefined) { * context snapshot always move together so a flush can't drop one. */ type QueuedEntry = { draft: DraftSnapshot - context: ContextElement[] | undefined + context: ContextElement[] } /** Plan mode's view of the chat it runs in. A function rather than an object literal in the @@ -537,7 +539,6 @@ export class AIChatManager implements ChatViewHost { /** Markdown artifacts the copilot created for the current session. */ artifacts = new SessionArtifactsStore() abortController: AbortController | undefined = undefined - inlineAbortController: AbortController | undefined = undefined // Flag to skip Responses API if it's not available (e.g., Azure region doesn't support it) skipResponsesApi = $state(false) @@ -691,6 +692,8 @@ export class AIChatManager implements ChatViewHost { * mounts of it each reorder the schema SchemaForm edits in place. */ isRunFormTabOpen?: (toolCallId: string) => boolean openArtifact?: (artifactId: string, name: string, version?: ArtifactVersionTarget) => void + /** Show an image in the session's preview panel. Set by a session runtime only. */ + openImage?: (source: ImageSource, label: string) => void closeArtifact?: (artifactId: string) => void openS3File?: (file: S3FileRef) => void #loading = $state<boolean>(false) @@ -2882,7 +2885,8 @@ export class AIChatManager implements ChatViewHost { #takeQueue(): QueuedEntry { const taken = { draft: this.#queuedDraft.take(), - context: this.queuedContext + // Not undefined, which would send the live selection: that of the next message. + context: this.queuedContext ?? [] } this.queuedContext = undefined this.#queueSendsMidTurnIn = undefined @@ -2914,7 +2918,7 @@ export class AIChatManager implements ChatViewHost { images: queued.draft.images, files: queued.draft.files }) - if (queued.context?.length) { + if (queued.context.length) { const merged = [...queued.context] for (const c of this.queuedContext ?? []) { if (!merged.some((m) => isSameContextElement(m, c))) { @@ -2925,33 +2929,23 @@ export class AIChatManager implements ChatViewHost { } } - /** Put a draft's pinned DOM selector chips back as the live selection, so the - * restored draft and the selection stay coherent (its instruction targets the - * element it was written for). No-op when the draft pinned no DOM chips, so a - * plain-text draft leaves the live selection untouched. + /** Put a draft's pinned picks back as the live selection, so the restored draft and the + * selection stay coherent (its instruction targets what it was written for). No-op when + * the draft pinned none, so a plain-text draft leaves the live selection untouched. * * `keepExisting` when the restored text was merged into a draft the user was * already writing: that draft's own chips must survive alongside, or its - * instruction — still sitting in the composer — would be retargeted at this - * draft's element. Otherwise the restore replaces, since any chip selected - * since belongs to a draft that is being replaced too. */ - #restoreDomContext(context: ContextElement[] | undefined, keepExisting = false) { - const domChips = (context ?? []).filter((c) => c.type === 'app_dom_selector') - if (domChips.length === 0) return - const existing = keepExisting - ? (this.contextManager?.getSelectedContext().filter((c) => c.type === 'app_dom_selector') ?? - []) - : [] - this.contextManager?.clearSelectedDomElements() - // addSelectedDomElement dedups on (selector, appPath), so a chip both drafts - // share collapses to one. - for (const c of [...domChips, ...existing]) { - this.contextManager?.addSelectedDomElement(c) - } + * instruction, still sitting in the composer, would be retargeted at this + * draft's pick. Otherwise the restore replaces preview elements, since any + * selected since belongs to a draft that is being replaced too. */ + #restorePickContext(context: ContextElement[] | undefined, keepExisting = false) { + const picks = (context ?? []).filter(isPickContext) + if (picks.length === 0) return + this.contextManager?.restorePickContext(picks, keepExisting) } /** Give back the mentions a send carried when its text returns to the composer, - * so its `@` tokens still have entries to bind to. Additive, unlike the DOM + * so its `@` tokens still have entries to bind to. Additive, unlike the pick * restore above: dropping the entries this send did not carry would strand the * tokens naming them in a draft whose text now shares the same composer. * @@ -2977,7 +2971,9 @@ export class AIChatManager implements ChatViewHost { * * Gated on `sendInFlight` as well as `loading`: `loading` only rises after a * send's attachment upkeep, so between the two a click would slip past. */ - sendOrQueue(text: string, context?: ContextElement[]) { + sendOrQueue(text: string, picks: PickContext[] = []) { + // The composer's own picks stay there: they belong to the draft being written in it. + const context = [...this.#contextWithoutPicks(), ...picks] if (this.loading || this.sendInFlight || this.sendPending) { this.queueMessage(text, [], context) return @@ -2985,6 +2981,10 @@ export class AIChatManager implements ChatViewHost { void this.sendRequest({ instructions: text, contextOverride: context }) } + #contextWithoutPicks(): ContextElement[] { + return this.contextManager.getSelectedContext().filter((c) => !isPickContext(c)) + } + /** Remove the queued message and put it back into the input, images included. */ dequeueMessage() { if (!this.#hasQueuedMessage()) { @@ -3000,27 +3000,31 @@ export class AIChatManager implements ChatViewHost { // the composer targets the element the draft was written for, not whatever // is selected now. If its text was prepended onto an existing draft, that // draft's chips are kept too — both instructions now share one composer. - this.#restoreDomContext(queued.context, mergedIntoDraft) + this.#restorePickContext(queued.context, mergedIntoDraft) // The queue aggregates several enqueues into one entry and records no // originating mode, so the mode now is the closest signal available. A // recall after a mid-turn mode switch can therefore miss a restore. this.#restoreMentionContext(queued.context, this.mode) } - /** Put what the user typed back where they can see it: into the input - * when it's mounted, otherwise back into the queue so it reappears with - * the chat panel instead of being silently dropped. */ + /** Put what the user typed back where they can see it, with its picks: into the input + * when it's mounted, beside the picks there, otherwise back into the queue so it reappears + * with the chat panel instead of being silently dropped. */ private restoreToInput( text: string, images: AttachedImage[] = [], - files: AttachedTextFile[] = [] + files: AttachedTextFile[] = [], + context: ContextElement[] = [] ): boolean { if (this.aiChatInput) { - return this.aiChatInput.prependText(text, images, files) === true + const mergedIntoDraft = this.aiChatInput.prependText(text, images, files) === true + this.#restorePickContext(context, true) + return mergedIntoDraft } // Merge onto anything already queued (see #restoreQueue) — replacing would // silently drop a message queued while this one was in flight. - this.#queuedDraft.prepend({ text, images, files }) + const draft = { text, images, files, pastes: [], blobs: [] } + this.#restoreQueue({ draft, context }) return false } @@ -3200,7 +3204,8 @@ export class AIChatManager implements ChatViewHost { access: this.#toolAccess, getChatId: () => this.historyManager.getCurrentChatId(), openArtifact: this.openArtifact, - openS3File: this.openS3File + openS3File: this.openS3File, + openImage: this.openImage } : {}), testActiveFlow: async (storagePath: string, args?: Record<string, any>, memoryId?: string) => @@ -3595,29 +3600,28 @@ export class AIChatManager implements ChatViewHost { } } - // Roll a turn that produced nothing usable back out of the transcript and - // hand its text back to the composer for editing/resending. `restoreToInput` - // is false when a queued message is about to take over (a user cancel with - // something queued) — then the rolled-back prompt is dropped rather than - // shoved back into the input, so the handoff to the queued message is clean. - private restoreUnsentTurn = async ( - displayLenAfterUser: number, - modelLenAfterUser: number, - instructions: string, - pastes: PasteAttachment[], - restoreToInput: boolean = true, - images: AttachedImage[] = [], - files: AttachedTextFile[] = [] - ): Promise<boolean> => { + /** Hand a rolled-back message back to the composer with its picks and mentions, or with none + * of them: on a draft that declined the text, they would retarget what is being written. */ + #returnToComposer( + draft: Pick<DraftSnapshot, 'text' | 'pastes' | 'images' | 'files'>, + context: ContextElement[] | undefined, + originMode: AIMode, + { replacePicks = false } = {} + ) { + const { text, pastes, images, files } = draft + if (!this.aiChatInput?.restoreInstructions(text, pastes, images, files)) return + this.#restorePickContext(context, !replacePicks) + this.#restoreMentionContext(context, originMode) + } + + // Roll a turn that produced nothing usable back out of the transcript. + #dropUnsentTurn(displayLenAfterUser: number, modelLenAfterUser: number) { this.displayMessages = this.displayMessages.slice(0, displayLenAfterUser - 1) this.messages = this.messages.slice(0, modelLenAfterUser - 1) // The rolled-back turn's files must not stay registered: the message // referencing them is gone, so leaving them would keep stale content // readable by the tools on later turns. this.#syncMessageFiles() - if (!restoreToInput) return false - // An occupied composer declines the restore and keeps its own draft. - return this.aiChatInput?.restoreInstructions(instructions, pastes, images, files) === true } // Bytes each live composer has staged toward its next send (committed @@ -3914,92 +3918,6 @@ export class AIChatManager implements ChatViewHost { } } - sendInlineRequest = async (instructions: string, selectedCode: string, selection: Selection) => { - // Validate inputs - if (!instructions.trim()) { - throw new Error('Instructions are required') - } - // Use a separate abort controller for inline requests to avoid interfering with main chat - this.inlineAbortController = new AbortController() - const lang = this.scriptEditorOptions?.lang ?? 'bun' - const selectedContext: ContextElement[] = [...this.contextManager.getSelectedContext()] - const startLine = selection.startLineNumber - const endLine = selection.endLineNumber - selectedContext.push({ - type: 'code_piece', - lang, - title: `L${startLine}-L${endLine}`, - startLine, - endLine, - content: selectedCode - }) - - const systemMessage: ChatCompletionSystemMessageParam = { - role: 'system', - content: prepareInlineChatSystemPrompt(lang, { - workflowAsCode: this.scriptEditorOptions?.workflowAsCode ?? false - }) - } - - let reply = '' - - try { - const userMessage = prepareScriptUserMessage(instructions, selectedContext) - const messages = [userMessage] - - const params = { - messages, - abortController: this.inlineAbortController, - callbacks: { - onNewToken: (token: string) => { - reply += token - }, - onMessageEnd: () => {}, - setToolStatus: () => {}, - removeToolStatus: () => {} - }, - systemMessage - } - - await this.chatRequest({ ...params }) - - // Validate we received a response - if (!reply.trim()) { - throw new Error('AI response was empty') - } - - // Try to extract new code from response - const newCodeMatch = reply.match(/<new_code>([\s\S]*?)<\/new_code>/i) - if (newCodeMatch && newCodeMatch[1]) { - const code = newCodeMatch[1].trim() - if (!code) { - throw new Error('AI response contained empty code block') - } - return code - } - - // Fallback: try to take everything after the last <new_code> tag - const lastNewCodeMatch = reply.match(/<new_code>([\s\S]*)/i) - if (lastNewCodeMatch && lastNewCodeMatch[1]) { - const code = lastNewCodeMatch[1].trim().replace(/```/g, '') - if (!code) { - throw new Error('AI response contained empty code block') - } - return code - } - - // If no code tags found, throw error with helpful message - throw new Error('AI response did not contain valid code. Please try rephrasing your request.') - } catch (error) { - // if abort controller is aborted, don't throw an error - if (this.inlineAbortController?.signal.aborted) { - return - } - console.error('Unexpected error in sendInlineRequest:', error) - throw new Error('An unexpected error occurred. Please try again.') - } - } - // Optional pre-flight hook called once per send, after the user's message // bubble + loading indicator are shown optimistically but before the request // goes out. Sessions use this to commit/materialise the workspace (creating a @@ -4117,13 +4035,7 @@ export class AIChatManager implements ChatViewHost { return undefined } - const { draft, context = [] } = this.#takeQueue() - // Pinned at enqueue, so consumed from the live selection as any pinned send does. - for (const c of context) { - if (c.type === 'app_dom_selector') { - this.contextManager?.removeSelectedDomElement(c.selector, c.appPath) - } - } + const { draft, context } = this.#takeQueue() if (this.mode === AIMode.SCRIPT || this.mode === AIMode.FLOW) { this.contextManager?.updateContextOnRequest({}) } @@ -4177,8 +4089,7 @@ export class AIChatManager implements ChatViewHost { } // The shared manager has no chat on screen: turns render only in a session's own chat. // One started here would still stream, spend tokens and apply tool calls, entirely - // off-screen, so refuse it. `sendInlineRequest` is exempt: the ⌘K widget renders its own - // composer inside Monaco. + // off-screen, so refuse it. if (this === aiChatManager) { console.error('sendRequest called with no chat UI mounted; dropping the turn') sendUserToast('This action needs the AI chat. Start an AI session to continue.', true) @@ -4214,7 +4125,8 @@ export class AIChatManager implements ChatViewHost { this.restoreToInput( expanded(chatDraft(options.instructions ?? this.instructions, options.pastes ?? [])), options.images, - options.files + options.files, + options.contextOverride ) } sendUserToast( @@ -4250,12 +4162,6 @@ export class AIChatManager implements ChatViewHost { // contextManager. Set whenever a send settles its context ahead of the // turn: a composer submit at the click, a queued message at enqueue. contextOverride?: ContextElement[] - /** Where `contextOverride` came from. 'pinned' (default): the chips were - * selected for THIS message, so they are consumed from the live selection - * on send. 'replay': an edit/retry resending an older message's context — - * those chips were consumed long ago, and removing them again would strip - * an identical selection the user has since made in the composer. */ - contextOverrideOrigin?: 'pinned' | 'replay' /** Auto-send of a queued draft: on preflight failure the caller re-queues * it, so the composer restore must not also fire (the draft would exist * twice — queue chip and composer). */ @@ -4329,6 +4235,8 @@ export class AIChatManager implements ChatViewHost { // resolved to `/clear` or `/compact` must not strand its resend reservation. if (COMPACT_COMMAND_RE.test(trimmed) || CLEAR_COMMAND_RE.test(trimmed)) { this.#releaseOutgoingReservation(reservationKey) + // It carries no pick either. + this.#restorePickContext(options.contextOverride, true) } // `/compact`: summarize the conversation locally to free up context. if (COMPACT_COMMAND_RE.test(trimmed)) { @@ -4398,17 +4306,16 @@ export class AIChatManager implements ChatViewHost { // restore is keyed to requestedMode: a GLOBAL submit whose mode // flipped during the upkeep awaits above still gets its mentions // back, while a send that started outside GLOBAL consumed none. - const taken = - this.aiChatInput?.restoreInstructions( - this.instructions, + this.#returnToComposer( + { + text: this.instructions, pastes, - options.images ?? [], - options.files ?? [] - ) === true - if (taken) { - this.#restoreDomContext(options.contextOverride, true) - this.#restoreMentionContext(options.contextOverride, requestedMode) - } + images: options.images ?? [], + files: options.files ?? [] + }, + options.contextOverride, + requestedMode + ) } return false } @@ -4436,7 +4343,7 @@ export class AIChatManager implements ChatViewHost { // that does not write a token would break that and need one here. if (!this.instructions.trim() && files.length === 0) { sendUserToast(`${sendModel.model} can't read images. Switch to a vision model first.`, true) - if (!options.queued) this.restoreToInput('', requestedImages) + if (!options.queued) this.restoreToInput('', requestedImages, [], options.contextOverride) return false } sendUserToast( @@ -4461,7 +4368,12 @@ export class AIChatManager implements ChatViewHost { // awaits above occupies the composer, and this restore must merge // into it (or queue), never be refused by it. if (!options.queued) { - this.restoreToInput(expanded(chatDraft(this.instructions, pastes)), images, files) + this.restoreToInput( + expanded(chatDraft(this.instructions, pastes)), + images, + files, + options.contextOverride + ) } sendUserToast('This session is running in another tab. Your message was kept.', true) } @@ -4519,16 +4431,11 @@ export class AIChatManager implements ChatViewHost { console.error('AIChatManager beforeSend hook failed', e) rollbackOptimisticSend() if (!options.queued) { - // Mentions were consumed at submit, so they come back with the text or - // not at all. Only when the composer took it: it declines when the - // user has started a new draft, and restoring then would put these - // mentions on that draft and every turn after it. - const taken = - this.aiChatInput?.restoreInstructions(this.instructions, pastes, images, files) === true - if (taken) { - this.#restoreDomContext(options.contextOverride, true) - this.#restoreMentionContext(options.contextOverride, requestedMode) - } + this.#returnToComposer( + { text: this.instructions, pastes, images, files }, + options.contextOverride, + requestedMode + ) } sendUserToast( `Could not prepare the session before sending: ${ @@ -4586,14 +4493,11 @@ export class AIChatManager implements ChatViewHost { }) if (accepted === false) this.#restoreQueue(next) } else { - // Same pairing as the beforeSend catch above: mentions ride back with the - // text, only if the composer took it. - const taken = - this.aiChatInput?.restoreInstructions(this.instructions, pastes, images, files) === true - if (taken) { - this.#restoreDomContext(options.contextOverride, true) - this.#restoreMentionContext(options.contextOverride, requestedMode) - } + this.#returnToComposer( + { text: this.instructions, pastes, images, files }, + options.contextOverride, + requestedMode + ) } return true } @@ -4694,27 +4598,16 @@ export class AIChatManager implements ChatViewHost { // it belongs to whatever the user has selected since. Otherwise read the // current selection. const oldSelectedContext = - options.contextOverride ?? this.contextManager?.getSelectedContext() ?? [] - // DOM selector chips are one-shot: they ride with this message (captured in + options.contextOverride ?? + (options.synthetic + ? this.#contextWithoutPicks() + : (this.contextManager?.getSelectedContext() ?? [])) + // Pick chips are one-shot: they ride with this message (captured in // oldSelectedContext) and render above it, but must not persist in the input - // for the next turn. Clearing here leaves oldSelectedContext untouched. - if (options.contextOverrideOrigin === 'replay') { - // Edit/retry: the override is a copy of an already-sent message's - // context, consumed on its original send. The live selection belongs to - // the composer's own draft — touching it here would strip it. - } else if (options.contextOverride) { - // A pinned submit consumes only the chips it carried. Drop just those - // from the live selection (still there if the user didn't re-select); a - // newer selection made since is left intact. - for (const c of options.contextOverride) { - if (c.type === 'app_dom_selector') { - // Match appPath too: another app's live chip can share this - // selector, and dropping it would discard a newer selection. - this.contextManager?.removeSelectedDomElement(c.selector, c.appPath) - } - } - } else { - this.contextManager?.clearSelectedDomElements() + // for the next turn. Whoever pinned a snapshot has already taken them out: what + // is live then, or when the client sends, is the composer's next message's. + if (!options.contextOverride && !options.synthetic) { + this.contextManager?.consumePickContext() } if (this.mode === AIMode.SCRIPT || this.mode === AIMode.FLOW) { this.contextManager?.updateContextOnRequest(options) @@ -4795,7 +4688,7 @@ export class AIChatManager implements ChatViewHost { } : m ) - // For restoreUnsentTurn: the compact composer form (with paste tokens), + // For the restore after a rollback: the compact composer form (with paste tokens), // not the expanded LLM text, plus the rollback anchor after the user turn. const sentInstructions = this.instructions const sentPastes = pastes @@ -4874,7 +4767,7 @@ export class AIChatManager implements ChatViewHost { this.modifiedItems ? [...this.modifiedItems] : undefined ) } - // Rollback anchors for restoreUnsentTurn: captured after compaction so + // Rollback anchors for #dropUnsentTurn: captured after compaction so // they index into the (possibly compacted) stored history. The summary // path shrinks displayMessages too, so the display anchor must also be // read here, not before compaction. @@ -5109,27 +5002,16 @@ export class AIChatManager implements ChatViewHost { // about to auto-send (see the flush below) — drop the rolled-back // prompt instead of restoring it to the input so the handoff is clean. const willAutoSendQueued = this.wasCancelledByUser() && this.#hasQueuedMessage() - const textRestored = await this.restoreUnsentTurn( - displayLenAfterUser, - modelLenAfterUser, - sentInstructions, - sentPastes, - !willAutoSendQueued, - sentImages, - files - ) - // restoreUnsentTurn hands the text/pastes/images back for a resend, but - // the DOM selector chips were already consumed from the live selection - // before the request went out. Restore this turn's own chips so the - // resend keeps its element scope — replacing (not merging) any chips - // selected during the stream, so the restored draft stays coherent. - // Only when the composer actually took the text back: on a queued-message - // handoff, or when a draft typed during the stream made the composer - // decline, this prompt is dropped — restoring its chips would then - // retarget whatever draft is sitting there. - if (textRestored) { - this.#restoreDomContext(oldSelectedContext) - this.#restoreMentionContext(oldSelectedContext, requestedMode) + this.#dropUnsentTurn(displayLenAfterUser, modelLenAfterUser) + if (!willAutoSendQueued) { + // Elements picked during the stream are replaced, so that the restored + // draft stays coherent. + this.#returnToComposer( + { text: sentInstructions, pastes: sentPastes, images: sentImages, files }, + oldSelectedContext, + requestedMode, + { replacePicks: true } + ) } if (this.displayMessages.length === 0) { // saveChat no-ops on an empty transcript; the chat persisted earlier @@ -5331,15 +5213,6 @@ export class AIChatManager implements ChatViewHost { this.cancelLoadingTools() } - cancelInlineRequest = (reason?: string) => { - const cancelReason = reason ?? 'inline_cancelled' - console.log('cancelling inline request:', { - reason: cancelReason, - inlineAbortController: this.inlineAbortController - }) - this.inlineAbortController?.abort(cancelReason) - } - /** * The images of a stored user turn as the model saw them. Anything resending * a turn (retry, edit) must read them from here, never from the transcript @@ -5445,16 +5318,15 @@ export class AIChatManager implements ChatViewHost { // the element the message was about. An edit passes `editedContext` (the edit // box was seeded from this message's chips and the user may have changed // them); a bare Retry passes nothing and falls back to the original - // contextElements. `undefined` for modes that don't attach context leaves the - // live-selection behavior. An empty array is a deliberate "no context". + // contextElements. A message stored without any gets an empty array, as `undefined` + // would send the live selection, which is the composer's. this.instructions = newContent ?? userMessage.content // Prune the truncated messages' file registrations BEFORE the resend // re-registers its own — the other way around would delete the fresh rows. this.#syncMessageFiles() this.sendRequest({ pastes: pastes ?? userMessage.pastes, - contextOverride: editedContext ?? userMessage.contextElements, - contextOverrideOrigin: 'replay', + contextOverride: editedContext ?? userMessage.contextElements ?? [], images: images ?? sentImages, // The bubble copy is authoritative for files: the API message carries // only a reference (content lives in the store), so nothing ever strips @@ -5464,16 +5336,8 @@ export class AIChatManager implements ChatViewHost { }) } - addSelectedLinesToContext = ( - lines: string, - startLine: number, - endLine: number, - moduleId?: string - ) => { - if (!moduleId) { - this.changeMode(AIMode.SCRIPT) - } - this.contextManager?.addSelectedLinesToContext(lines, startLine, endLine, moduleId) + attachCodeSelection(selection: CodeSelection) { + this.contextManager.addCodeSelection(selection) this.focusInput() } diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts index 8e4716d275..ff79739f1a 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts @@ -9,6 +9,7 @@ import type { DisplayMessage } from './shared' import type { AttachedImage } from './imageUtils' import { AIChatManager, AIMode, AIAutonomyMode, aiChatManager } from './AIChatManager.svelte' import { AIWorkMode, USE_MODE_WITHDRAWN } from './workMode' +import { createAppDomSelectorElement, createCodeSelection } from './context' import { makePasteToken } from './pasteTokens' import { PLAN_MODE_MESSAGES } from './planModeMessages' import { runChatLoop } from './chatLoop' @@ -1323,6 +1324,17 @@ describe('AIChatManager user questions', () => { }) }) +function pick(content: string, line = 1) { + return createCodeSelection( + { kind: 'script', path: 'f/a/b' }, + { content, startLine: line, endLine: line, lang: 'bun' } + ) +} + +function element(selector: string) { + return createAppDomSelectorElement({ selector, appPath: 'f/app', tagName: 'div' }) +} + describe('AIChatManager queued messages', () => { const model = { provider: 'openai', model: 'gpt-4o' } @@ -1639,6 +1651,14 @@ describe('AIChatManager queued messages', () => { .filter((c) => c.type === 'app_dom_selector') .map((c) => c.selector) ).toEqual(['div.a']) + + // Nor when the message was stored without context. + seed() + delete (manager.displayMessages[0] as any).contextElements + manager.restartGeneration(0) + await vi.waitFor(() => expect(manager.displayMessages[0]).toHaveProperty('contextElements')) + expect(sentChipSelectors()).toEqual([]) + expect(cm.getSelectedContext()).toEqual([chipA]) }) // The loop, not the send, owns the vision strip: it re-applies it per iteration @@ -2528,7 +2548,7 @@ describe('AIChatManager queued messages', () => { const input = createInputMock() const manager = createManager(input) replyWith('done') - // cancel before any usable output → the rollback (restoreUnsentTurn) path + // cancel before any usable output → the rollback path mocks.runChatLoop.mockImplementationOnce(async ({ abortController }: any) => { abortController.abort('user_cancelled') throw new Error('aborted') @@ -2950,8 +2970,7 @@ describe('AIChatManager queued messages', () => { await manager.sendRequest({ instructions: 'why does this retry', - contextOverride: carried, - contextOverrideOrigin: 'pinned' + contextOverride: carried }) expect(cm.getSelectedContext()).toEqual([mention]) @@ -2975,8 +2994,7 @@ describe('AIChatManager queued messages', () => { await manager.sendRequest({ instructions: 'why does this retry', - contextOverride: [mention], - contextOverrideOrigin: 'pinned' + contextOverride: [mention] }) expect(cm.getSelectedContext()).toEqual([mention]) @@ -2995,8 +3013,7 @@ describe('AIChatManager queued messages', () => { const pending = manager.sendRequest({ instructions: 'describe this image', images: [{ id: 'img-1', dataUrl: 'data:image/png;base64,AAAA' } as any], - contextOverride: [mention], - contextOverrideOrigin: 'pinned' + contextOverride: [mention] }) manager.mode = AIMode.SCRIPT await pending @@ -3037,6 +3054,73 @@ describe('AIChatManager queued messages', () => { expect(chips.map((c) => c.selector)).toEqual(['div.a']) }) + it('carries code attached in a session on its next message, and only there', async () => { + replyWith('done') + const manager = createManager(createInputMock()) + manager.mode = AIMode.GLOBAL + manager.isSessionChat = true + const selection = pick('return 1', 2) + manager.listenForContextChange({}, 'parent') + manager.attachCodeSelection(selection) + // The composer's context is rebuilt whenever the page's workspace or its schemas change. + manager.listenForContextChange({}, 'parent') + manager.listenForContextChange({}, 'fork') + expect(manager.mode).toBe(AIMode.GLOBAL) + + await manager.sendRequest({ instructions: 'make it 2' }) + + const { messages } = mocks.runChatLoop.mock.calls.at(-1)![0] as any + expect(messages.at(-1).content).toContain('path: f/a/b, lines 2-2:\n```bun\nreturn 1\n```') + expect(manager.contextManager.getSelectedContext()).toEqual([]) + }) + + it('sends a queued message with its own picks and leaves the next one its own', async () => { + replyWith('done') + const manager = createManager(createInputMock()) + manager.mode = AIMode.GLOBAL + manager.queueMessage('first', [], [pick('before')]) + // The lines change and are queued again, then picked once more as they were at first. + manager.queueMessage('second', [], [pick('after')]) + manager.attachCodeSelection(pick('before')) + + await manager.sendRequest({ instructions: 'running', contextOverride: [] }) + + const { messages } = mocks.runChatLoop.mock.calls.at(-1)![0] as any + expect(messages.at(-1).content).toContain('before') + expect(messages.at(-1).content).toContain('after') + expect(manager.contextManager.getSelectedContext()).toEqual([pick('before')]) + }) + + it('leaves what is attached for the next message out of one queued without it', async () => { + replyWith('done') + const manager = createManager(createInputMock()) + manager.mode = AIMode.GLOBAL + const selection = pick('return 1', 2) + manager.queueMessage('queued') + manager.attachCodeSelection(selection) + + await manager.sendRequest({ instructions: 'running', contextOverride: [] }) + + const { messages } = mocks.runChatLoop.mock.calls.at(-1)![0] as any + expect(messages.at(-1).content).toContain('queued') + expect(messages.at(-1).content).not.toContain('SELECTED CODE') + expect(manager.contextManager.getSelectedContext()).toEqual([selection]) + }) + + it('leaves code attached in the composer there when a prompt sent past it comes back', () => { + const manager = createManager(createInputMock()) + manager.attachCodeSelection(pick('for the composer')) + manager.loading = true + manager.sendOrQueue('make it red', [element('div.prompt')]) + + manager.dequeueMessage() + + expect(manager.contextManager.getSelectedContext()).toEqual([ + element('div.prompt'), + pick('for the composer') + ]) + }) + // Restoration is only coherent when the text it belongs to actually lands in the // composer. Both cases below leave another draft sitting there, so replacing its // chips would silently retarget an instruction the user is still writing. @@ -3151,8 +3235,7 @@ describe('AIChatManager queued messages', () => { const accepted = await manager.sendRequest({ instructions: '@f/etl/sync fix this', - contextOverride: [mention], - contextOverrideOrigin: 'pinned' + contextOverride: [mention] }) expect(accepted).toBe(false) @@ -3172,8 +3255,7 @@ describe('AIChatManager queued messages', () => { await manager.sendRequest({ instructions: '@f/etl/sync fix this', - contextOverride: [mention], - contextOverrideOrigin: 'pinned' + contextOverride: [mention] }) expect(mocks.runChatLoop).not.toHaveBeenCalled() @@ -3214,8 +3296,7 @@ describe('AIChatManager queued messages', () => { await manager.sendRequest({ instructions: '@f/etl/sync fix this', - contextOverride: [mention], - contextOverrideOrigin: 'pinned' + contextOverride: [mention] }) expect(manager.contextManager.getSelectedContext()).toEqual([]) @@ -3234,8 +3315,7 @@ describe('AIChatManager queued messages', () => { await manager.sendRequest({ instructions: 'fix this', - contextOverride: [mention], - contextOverrideOrigin: 'pinned' + contextOverride: [mention] }) expect(manager.contextManager.getSelectedContext()).toEqual([]) @@ -5043,6 +5123,25 @@ describe('AIChatManager cross-tab run seams', () => { expect(manager.queuedMessage).toBe('race loser') }) + it.each([ + ['at the start of the send', () => true], + // Announced during the send's own awaits. + ['once it is under way', (reads: number) => reads > 1] + ])('keeps the pick of a refused prompt, refused %s', async (_, held) => { + const manager = new AIChatManager() + manager.isSessionChat = true + manager.mode = AIMode.GLOBAL + let reads = 0 + manager.runHeldElsewhereResolver = () => held(++reads) + const selection = element('div.prompt') + + manager.sendOrQueue('make it red', [selection]) + + await vi.waitFor(() => expect(manager.queuedMessage).toBe('make it red')) + expect(mocks.runChatLoop).not.toHaveBeenCalled() + expect(manager.queuedContext).toEqual([selection]) + }) + // A synthetic (auto-resume) prompt is client-authored: a refusal must // release it rather than hand it back as a draft the user never wrote — // staged instructions would otherwise block every later auto-resume. diff --git a/frontend/src/lib/components/copilot/chat/AIChatMessage.svelte b/frontend/src/lib/components/copilot/chat/AIChatMessage.svelte index f521fcce1d..c0344ec8f4 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatMessage.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatMessage.svelte @@ -13,6 +13,7 @@ import { messageDraft, segments } from './chatDraft' import { lineCountLabel } from './pasteTokens' import ExpandableImage from '$lib/components/common/image/ExpandableImage.svelte' + import { imageContentKey } from './files/imageFiles' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() @@ -178,6 +179,13 @@ src={image.dataUrl} alt={image.name ?? 'attached image'} class="max-h-40 max-w-[min(20rem,100%)] rounded-lg border border-border-light" + onOpen={chatHost.openImage + ? () => + chatHost.openImage?.( + { kind: 'message', hash: imageContentKey(image.dataUrl) }, + image.name ?? 'Image' + ) + : undefined} /> {/each} </div> diff --git a/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte b/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte index 082760f12f..9aeec52b6d 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte @@ -18,7 +18,7 @@ its block on a detail page laid over the list, like a skill in the Skills sectio import Path from '$lib/components/Path.svelte' import SimpleEditor from '$lib/components/SimpleEditor.svelte' import Markdown from 'svelte-exmarkdown' - import { gfmPlugin } from 'svelte-exmarkdown/gfm' + import { markdownPlugins } from '$lib/components/markdownPlugins' import { markdownProse } from '$lib/components/markdownProse' import { applySavedWorkspaceCopilotInfo, @@ -893,7 +893,7 @@ its block on a detail page laid over the list, like a skill in the Skills sectio <div class="{folderMode === 'view' ? 'block' : 'hidden'} {markdownProse.sm}"> <div class="border rounded-md p-3 overflow-auto space-y-2"> {#if folderContent.trim()} - <Markdown md={folderContent} plugins={[gfmPlugin()]} /> + <Markdown md={folderContent} plugins={markdownPlugins} /> {:else} <span class="text-xs text-hint">Empty.</span> {/if} diff --git a/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte b/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte index 841966a687..1e4e0d28e2 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte @@ -7,6 +7,7 @@ import CodeDisplay from './script/CodeDisplay.svelte' import LinkRenderer from './LinkRenderer.svelte' import MarkdownImage from './MarkdownImage.svelte' + import { messageS3Object } from './messageS3Object' import { extractCandidatePaths, remarkWindmillPaths, @@ -88,15 +89,7 @@ // A flow step can return a file rather than text; the raw JSON would be // unreadable, so hand it to the result viewer instead of the markdown renderer. - const s3Object = $derived.by(() => { - if (!message.content.startsWith('{')) return undefined - try { - const parsed = JSON.parse(message.content) - return parsed?.type === 'windmill_s3_object' && parsed?.s3 ? parsed : undefined - } catch { - return undefined - } - }) + const s3Object = $derived(messageS3Object(message.content)) const candidatePaths = $derived(extractCandidatePaths(message.content)) const reasoningPlugins = [gfmPlugin(), { renderer: { a: LinkRenderer, img: MarkdownImage } }] diff --git a/frontend/src/lib/components/copilot/chat/AssistantSkillsSection.svelte b/frontend/src/lib/components/copilot/chat/AssistantSkillsSection.svelte index 947fb562d3..172c67ab73 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantSkillsSection.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantSkillsSection.svelte @@ -19,7 +19,7 @@ and the actions that create, edit, import and delete them. import Path from '$lib/components/Path.svelte' import SimpleEditor from '$lib/components/SimpleEditor.svelte' import Markdown from 'svelte-exmarkdown' - import { gfmPlugin } from 'svelte-exmarkdown/gfm' + import { markdownPlugins } from '$lib/components/markdownPlugins' import { markdownProse } from '$lib/components/markdownProse' import { userStore } from '$lib/stores' import { sendUserToast } from '$lib/toast' @@ -1157,7 +1157,7 @@ What the assistant should do when this skill applies. <p class="text-xs text-secondary">{parsed.description}</p> {/if} <div class="border rounded-md p-3 overflow-auto space-y-2 {markdownProse.sm}"> - <Markdown md={parsed.instructions} plugins={[gfmPlugin()]} /> + <Markdown md={parsed.instructions} plugins={markdownPlugins} /> </div> </div> <div class="{detailMode === 'edit' ? 'flex' : 'hidden'} flex-col gap-3"> diff --git a/frontend/src/lib/components/copilot/chat/ContextElementBadge.svelte b/frontend/src/lib/components/copilot/chat/ContextElementBadge.svelte index dd94b076ea..73d26f1906 100644 --- a/frontend/src/lib/components/copilot/chat/ContextElementBadge.svelte +++ b/frontend/src/lib/components/copilot/chat/ContextElementBadge.svelte @@ -37,6 +37,8 @@ // (the composer keeps every badge the same size). const COMPACT_TYPES = new Set([ 'app_dom_selector', + 'code_piece', + 'flow_module_code_piece', 'workspace_app', 'workspace_agent', 'workspace_script', diff --git a/frontend/src/lib/components/copilot/chat/ContextManager.svelte.ts b/frontend/src/lib/components/copilot/chat/ContextManager.svelte.ts index 18190290b5..cf7ebf58fa 100644 --- a/frontend/src/lib/components/copilot/chat/ContextManager.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/ContextManager.svelte.ts @@ -4,9 +4,14 @@ import { SQLSchemaLanguages, type DBSchemas } from '$lib/stores' import { diffLines } from 'diff' import { createAppDomSelectorElement, + isCodeSelection, isMentionContext, + isPickContext, + isSameCodeRange, + isSameContextElement, + type CodeSelection, type ContextElement, - type FlowModuleElement + type PickContext } from './context' import type { FlowModule } from '$lib/gen' @@ -77,13 +82,13 @@ export default class ContextManager { this.availableContext = [] if (!workspace || (this.workspace !== undefined && this.workspace !== workspace)) { this.workspace = workspace - this.selectedContext = [] + // Code selections are of the session's own items, not of the workspace browsed. + this.selectedContext = currentlySelectedContext.filter(isCodeSelection) return } this.workspace = workspace this.selectedContext = currentlySelectedContext.filter( - (context) => - isMentionContext(context) + (context) => isMentionContext(context) || isCodeSelection(context) ) } @@ -250,11 +255,11 @@ export default class ContextManager { // Seed with the (refreshed) code block + everything else previously // selected. The filter further down validates each entry against - // newAvailableContext (and the per-type allowlist for code_piece / - // workspace_*); types that are auto-derived (diff/error/db) survive - // when they're still in availableContext, user-picked workspace refs - // survive unconditionally, and `code` is excluded from the carryover - // because we just rebuilt it. + // newAvailableContext (and the per-type allowlist for workspace_*); + // types that are auto-derived (diff/error/db) survive when they're + // still in availableContext, user-picked workspace refs survive + // unconditionally, and `code` is excluded from the carryover because + // we just rebuilt it. let newSelectedContext: ContextElement[] = [ { type: 'code', @@ -285,7 +290,6 @@ export default class ContextManager { newSelectedContext = newSelectedContext .filter( (c) => - (c.type === 'code_piece' && scriptOptions.getCode().includes(c.content)) || c.type === 'code' || // Workspace references are user-picked via @-mention and not in // availableContext; preserve so badges survive editor refreshes. @@ -336,6 +340,24 @@ export default class ContextManager { this.selectedContext = this.selectedContext.filter((c) => !isMentionContext(c)) } + consumePickContext() { + this.selectedContext = this.selectedContext.filter((c) => !isPickContext(c)) + } + + /** Put picks back with their message, beside those already selected or in place of them. + * Selected code always stays: it names its own lines, so it retargets no other message. */ + restorePickContext(picks: PickContext[], keepExisting: boolean) { + const rest = this.selectedContext.filter((c) => !isPickContext(c)) + const existing = this.selectedContext.filter( + (c) => isCodeSelection(c) || (keepExisting && isPickContext(c)) + ) + this.selectedContext = [ + ...rest, + ...picks, + ...existing.filter((c) => !picks.some((p) => isSameContextElement(p, c))) + ] + } + getAvailableContext() { return this.availableContext } @@ -344,52 +366,12 @@ export default class ContextManager { this.scriptOptions = scriptOptions } - addSelectedLinesToContext(lines: string, startLine: number, endLine: number, moduleId?: string) { - const title = moduleId ? `${moduleId} L${startLine}-L${endLine}` : `L${startLine}-L${endLine}` - if ( - !this.scriptOptions || - this.selectedContext.find( - (c) => - (c.type === 'code_piece' && c.title === title) || - (c.type === 'flow_module_code_piece' && c.id === moduleId && c.title === title) - ) - ) { - return - } - if (moduleId) { - const module = [...this.availableContext, ...this.selectedContext].find( - (c) => c.type === 'flow_module' && c.id === moduleId - ) as FlowModuleElement - if (!module) { - console.error('Module not found', moduleId) - return - } - this.selectedContext = [ - ...this.selectedContext, - { - type: 'flow_module_code_piece', - id: moduleId, - title: title, - startLine, - endLine, - content: lines, - lang: this.scriptOptions.lang, - value: module.value - } - ] - } else { - this.selectedContext = [ - ...this.selectedContext, - { - type: 'code_piece', - title: title, - startLine, - endLine, - content: lines, - lang: this.scriptOptions.lang - } - ] - } + /** Attach selected code. Lines already attached are replaced, as their code may have changed. */ + addCodeSelection(selection: CodeSelection) { + this.selectedContext = [ + ...this.selectedContext.filter((c) => !isCodeSelection(c) || !isSameCodeRange(c, selection)), + selection + ] } /** @@ -481,7 +463,6 @@ export default class ContextManager { } updateContextOnRequest(options: { removeDiff?: boolean; addBackCode?: boolean }) { - this.selectedContext = this.selectedContext.filter((c) => c.type !== 'code_piece') if (options.removeDiff) { this.selectedContext = this.selectedContext.filter((c) => c.type !== 'diff') } diff --git a/frontend/src/lib/components/raw_apps/InlineElementPrompt.svelte b/frontend/src/lib/components/copilot/chat/InlinePrompt.svelte similarity index 51% rename from frontend/src/lib/components/raw_apps/InlineElementPrompt.svelte rename to frontend/src/lib/components/copilot/chat/InlinePrompt.svelte index 721b3b4bfe..b1fde5ca90 100644 --- a/frontend/src/lib/components/raw_apps/InlineElementPrompt.svelte +++ b/frontend/src/lib/components/copilot/chat/InlinePrompt.svelte @@ -4,20 +4,19 @@ import { ArrowUp } from 'lucide-svelte' let { - x, - y, - label, - inNewSession = false, + position = undefined, + label = undefined, + ariaLabel, onSend, onClose }: { - /** Fixed-position anchor (host viewport coords), top-left of the input. */ - x: number - y: number - /** Short element label shown as the placeholder hint (e.g. "button.btn"). */ - label: string - /** Sending leaves this page for a new AI session, so the hint says so. */ - inNewSession?: boolean + /** Fixed-position anchor (host viewport coords), top-left of the input. Without one, the + * box sits where its parent puts it. */ + position?: { x: number; y: number } + /** Short name of what the prompt is about, shown as the placeholder hint. Without one, the + * hint says that sending leaves this page for a new AI session. */ + label?: string + ariaLabel: string /** Resolving to `false` keeps the box open with its text. */ onSend: (prompt: string) => void | Promise<boolean | void> onClose: () => void @@ -27,11 +26,15 @@ let sending = $state(false) let textarea = $state<HTMLTextAreaElement | undefined>(undefined) - // Focus when the anchor first appears (the element was just selected). + // Focus when the anchor first appears (its subject was just selected). $effect(() => { textarea?.focus() }) + export function focus() { + textarea?.focus() + } + async function submit() { const v = value.trim() if (!v || sending) return @@ -44,29 +47,38 @@ } </script> -<!-- Floating mini-composer anchored to the selected element in the preview. Sends - the prompt to the session chat (or a new session) with that element as context. --> +<!-- Floating mini-composer anchored to a pick: an element of the preview, or selected code. + Sends the prompt to the session chat (or a new session) with that pick as context. --> <!-- The whole pill is the field: the border/focus-ring lives on this box and the send arrow sits inside it, centered against a single-line input. --> <div - class="fixed z-[10000] flex items-center gap-1 rounded-md border border-border-light bg-surface-input py-1 pl-1 pr-1 shadow-md transition-colors focus-within:border-border-selected" - style="left: {x}px; top: {y}px; width: 260px; max-width: calc(100vw - 16px);" + class="{position + ? 'fixed z-[10000]' + : ''} flex items-center gap-1 rounded-md border border-border-light bg-surface-input py-1 pl-1 pr-1 shadow-md transition-colors focus-within:border-border-selected" + style={position + ? `left: ${position.x}px; top: ${position.y}px; width: 260px; max-width: calc(100vw - 16px);` + : undefined} role="dialog" - aria-label="Prompt about the selected element" + aria-label={ariaLabel} > <textarea bind:this={textarea} bind:value use:autosize={{ maxHeight: '120px', minHeight: 20 }} rows={1} - placeholder={inNewSession ? 'Ask in a new AI session…' : `Ask about ${label}…`} + placeholder={label ? `Ask about ${label}…` : 'Ask in a new AI session…'} class="min-w-0 flex-1 resize-none !border-0 !bg-transparent !shadow-none px-1.5 !pt-[5px] !pb-[3px] text-xs leading-tight !ring-0 focus:!border-0 focus:!ring-0 focus:outline-none" - onkeydown={(e) => { - if (e.key === 'Enter' && !e.shiftKey) { + onkeydowncapture={(e) => { + // Capturing, as Monaco's own shortcuts run before a handler Svelte delegates to the root: + // over a code editor, Ctrl+Enter would run the code. + if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault() + e.stopPropagation() submit() } else if (e.key === 'Escape') { e.preventDefault() + // It closes the box alone, not the flow step an editor may be in. + e.stopPropagation() onClose() } }} diff --git a/frontend/src/lib/components/copilot/chat/ProviderModelSelector.svelte b/frontend/src/lib/components/copilot/chat/ProviderModelSelector.svelte index 4713b71355..5befafb341 100644 --- a/frontend/src/lib/components/copilot/chat/ProviderModelSelector.svelte +++ b/frontend/src/lib/components/copilot/chat/ProviderModelSelector.svelte @@ -2,14 +2,8 @@ import { ChevronDown, Brain } from 'lucide-svelte' import DropdownV2 from '$lib/components/DropdownV2.svelte' import Button from '$lib/components/common/button/Button.svelte' - import { - COPILOT_SESSION_MODEL_SETTING_NAME, - COPILOT_SESSION_PROVIDER_SETTING_NAME, - COPILOT_SESSION_REASONING_SETTING_NAME - } from '$lib/stores' - import { storeLocalSetting } from '$lib/utils' - import { copilotInfo, copilotSessionModel, tryResolveModelFor } from '$lib/aiStore' - import type { AIProvider } from '$lib/gen' + import { copilotInfo } from '$lib/aiStore' + import type { AIProvider, AIProviderModel } from '$lib/gen' import { getReasoningCapability, resolveEffectiveReasoning, @@ -17,14 +11,25 @@ type ReasoningProviderModel } from '../reasoningRegistry' + interface Props { + /** The model a request would send, as resolved from the pick. */ + model: ReasoningProviderModel | undefined + onPick: (pick: ReasoningProviderModel) => void + /** The models offered, when they are not the tab's workspace's (an AI session's). */ + models?: AIProviderModel[] + } + + let { model, onPick, models }: Props = $props() + let offered = $derived(models ?? $copilotInfo.aiModels) + let providerModel = $derived( - (tryResolveModelFor($copilotInfo, $copilotSessionModel) ?? { + (model ?? { model: 'No model', provider: 'No provider' }) as ReasoningProviderModel ) - let multipleModels = $derived($copilotInfo.aiModels.length > 1) + let multipleModels = $derived(offered.length > 1) let capability = $derived( getReasoningCapability(providerModel.provider as AIProvider, providerModel.model) @@ -35,25 +40,17 @@ let effortLabel = $derived(currentEffort ?? REASONING_OFF) function selectReasoning(value: string) { - const reasoning = value === REASONING_OFF ? REASONING_OFF : value - $copilotSessionModel = { - ...providerModel, - provider: providerModel.provider as AIProvider, - reasoning - } // Pin the current model selection so the reasoning choice persists with it. - storeLocalSetting(COPILOT_SESSION_MODEL_SETTING_NAME, providerModel.model) - storeLocalSetting(COPILOT_SESSION_PROVIDER_SETTING_NAME, providerModel.provider) - storeLocalSetting(COPILOT_SESSION_REASONING_SETTING_NAME, reasoning) + onPick({ ...providerModel, reasoning: value }) } </script> {#if multipleModels} <DropdownV2 items={() => - $copilotInfo.aiModels.map((m) => ({ + offered.map((m) => ({ displayName: m.model, - selected: m.model === providerModel.model, + selected: m.model === providerModel.model && m.provider === providerModel.provider, action: () => { // Carry the effort onto the new model only if it supports that level // ('off' only where the model can truly disable); otherwise drop it so @@ -64,10 +61,7 @@ carried === REASONING_OFF ? cap.canDisable : carried !== undefined && cap.levels.includes(carried) - $copilotSessionModel = { ...m, ...(keep ? { reasoning: carried } : {}) } - storeLocalSetting(COPILOT_SESSION_MODEL_SETTING_NAME, m.model) - storeLocalSetting(COPILOT_SESSION_PROVIDER_SETTING_NAME, m.provider) - storeLocalSetting(COPILOT_SESSION_REASONING_SETTING_NAME, keep ? carried : undefined) + onPick({ ...m, ...(keep ? { reasoning: carried } : {}) }) } }))} placement="bottom-end" diff --git a/frontend/src/lib/components/copilot/chat/ToolContentDisplay.svelte b/frontend/src/lib/components/copilot/chat/ToolContentDisplay.svelte index 9d1bf698f7..86e0c18988 100644 --- a/frontend/src/lib/components/copilot/chat/ToolContentDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/ToolContentDisplay.svelte @@ -2,6 +2,8 @@ import { Loader2, Copy, Check } from 'lucide-svelte' import { TOOL_PRETTIFY_MAP } from './shared' import { scrollFades } from './scrollFades.svelte' + import { copyToClipboard as writeClipboard } from '$lib/utils' + import { sendUserToast } from '$lib/toast' interface Props { title: string @@ -69,14 +71,23 @@ } } + // `formatJson` assigns into the object it formats, so it gets a snapshot, never the prop. + const formatted = $derived(hasContent ? formatJson($state.snapshot(content)) : '') + // Copies what the block shows: the error replaces the content on screen. Empty text gets + // no button, since the helper refuses it and that would read as a failed copy. + const copyText = $derived(error ? String(error) : formatted) + async function copyToClipboard() { - if (!hasContent) return - try { - await navigator.clipboard.writeText(formatJson(content)) + const text = copyText + if (!text) return + // The shared helper falls back to execCommand where `navigator.clipboard` is missing + // (plain-HTTP hosts other than localhost). Its success toast is off: the check icon says it. + const ok = await writeClipboard(text, false) + if (ok) { copied = true setTimeout(() => (copied = false), 1500) - } catch (err) { - console.error('Failed to copy:', err) + } else { + sendUserToast("Couldn't copy to clipboard", true) } } @@ -100,7 +111,7 @@ <span class="text-2xs text-hint"> {title}: </span> - {#if showCopy && hasContent && !streaming} + {#if showCopy && copyText && !streaming} <button class="p-1 rounded hover:bg-surface-secondary text-primary hover:text-secondary transition-opacity duration-200 opacity-0 group-hover:opacity-100 focus-visible:opacity-100" onclick={copyToClipboard} @@ -132,9 +143,7 @@ onscroll={measureFades} class="overflow-x-auto max-h-28 overflow-y-auto" > - <pre use:fadeContent class="text-2xs text-primary whitespace-pre-wrap" - >{formatJson($state.snapshot(content))}</pre - > + <pre use:fadeContent class="text-2xs text-primary whitespace-pre-wrap">{formatted}</pre> </div> {#if showFade && fades.bottom} <div diff --git a/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte b/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte index 38e5067481..83b76284c5 100644 --- a/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte @@ -13,6 +13,7 @@ BookOpen, Eye } from 'lucide-svelte' + import { imageContentKey } from './files/imageFiles' import { truncateRev } from '$lib/utils' import { EXIT_PLAN_MODE_TOOL, @@ -40,6 +41,13 @@ type ToolDisplayMessage } from './shared' import SecretRequestCard from './SecretRequestCard.svelte' + + // Only a loaded image: a reloaded chat holds a reference until its bytes come back. + function toolImageOpener(url: string): (() => void) | undefined { + const open = chatHost.openImage + if (!open || !url.startsWith('data:')) return undefined + return () => open({ kind: 'message', hash: imageContentKey(url) }, 'Screenshot') + } import ChatCollapsibleCard from './ChatCollapsibleCard.svelte' import { twMerge } from 'tailwind-merge' import { slide } from 'svelte/transition' @@ -428,6 +436,7 @@ src={message.imageUrl} alt="Image returned by the tool" class="max-h-48 max-w-full rounded border border-border-light" + onOpen={toolImageOpener(message.imageUrl)} /> </div> {/if} diff --git a/frontend/src/lib/components/copilot/chat/chatDraft.ts b/frontend/src/lib/components/copilot/chat/chatDraft.ts index 78bf38cdc2..292efaffcf 100644 --- a/frontend/src/lib/components/copilot/chat/chatDraft.ts +++ b/frontend/src/lib/components/copilot/chat/chatDraft.ts @@ -30,8 +30,7 @@ export function messageDraft(m: { content: string; pastes?: PasteAttachment[] }) /** * The ONLY way to read the model-bound / flattened text: paste tokens expanded - * to their full content. Used by the LLM prepare* path, the inline ⌘K path, and - * the saved-chat title. + * to their full content. Used by the LLM prepare* path and the saved-chat title. */ export function expanded(d: ChatDraft): string { return expandPasteTokens(d.text, d.pastes) diff --git a/frontend/src/lib/components/copilot/chat/chatViewHost.ts b/frontend/src/lib/components/copilot/chat/chatViewHost.ts index 498be71529..8821a9957c 100644 --- a/frontend/src/lib/components/copilot/chat/chatViewHost.ts +++ b/frontend/src/lib/components/copilot/chat/chatViewHost.ts @@ -14,7 +14,11 @@ import type { ScopeDecision } from './workingScope' import type { GroupingTools } from './toolGroups' import type { AttachedFilesStore } from './files/attachedFiles.svelte' import type { SessionArtifactsStore } from './artifacts/artifactsState.svelte' -import type { ArtifactVersionTarget, S3FileRef } from '$lib/components/sessions/previewRouter' +import type { + ArtifactVersionTarget, + ImageSource, + S3FileRef +} from '$lib/components/sessions/previewRouter' import type { FlowAIChatHelpers } from './flow/core' import type { AppAIChatHelpers } from './app/core' import type AIChatInput from './AIChatInput.svelte' @@ -26,13 +30,10 @@ export type ChatSendRequestOptions = { files?: AttachedTextFile[] blobs?: AttachedBlob[] /** Selected-context snapshot for this turn, in place of the live selection. Set - * whenever a send settles its context ahead of the turn. A host with no context + * whenever a send settles its context ahead of the turn, and the sender's to take out + * of the live selection, which the send leaves alone. A host with no context * of its own ignores it. */ contextOverride?: ContextElement[] - /** Where `contextOverride` came from. 'pinned': chips picked for THIS message, so - * they are consumed from the live selection on send. 'replay': an edit or retry - * resending an older message's context, already consumed long ago. */ - contextOverrideOrigin?: 'pinned' | 'replay' } /** @@ -208,6 +209,9 @@ export interface ChatViewHost { /** Opens a file of the workspace's object storage in the session's side panel; only a * session has one. */ openS3File?: (file: S3FileRef) => void + /** Opens an image in a preview panel beside the chat. Undefined where there is none, and + * a message image then expands in place. */ + openImage?: (source: ImageSource, label: string) => void flowAiChatHelpers?: FlowAIChatHelpers appAiChatHelpers?: AppAIChatHelpers } diff --git a/frontend/src/lib/components/copilot/chat/context.ts b/frontend/src/lib/components/copilot/chat/context.ts index b19645d7e9..906b2ca660 100644 --- a/frontend/src/lib/components/copilot/chat/context.ts +++ b/frontend/src/lib/components/copilot/chat/context.ts @@ -71,6 +71,15 @@ interface DiffElement { lang: ScriptLang | 'bunnative' } +/** The workspace item whose code an editor edits. */ +export type CodeSource = { + kind: 'script' | 'flow' | 'raw_app' | 'agent' + path: string + /** The part of the item the code is: a flow step's id, an app's runnable key, an agent's tool + * id, or a script's module file. Unset for a script's main file. */ + part?: string +} + export interface CodePieceElement { type: 'code_piece' content: string @@ -78,6 +87,8 @@ export interface CodePieceElement { endLine: number title: string lang: ScriptLang | 'bunnative' + /** Set on a selection attached to a session, whose chat edits items by path. */ + source?: CodeSource } export interface FlowModuleElement { @@ -99,6 +110,51 @@ export interface FlowModuleCodePieceElement extends Omit<CodePieceElement, 'type value: FlowModuleElement['value'] } +/** Code selected in an editor and attached to a session's message. */ +export type CodeSelection = (CodePieceElement | FlowModuleCodePieceElement) & { + source: CodeSource +} + +export function isCodeSelection(c: ContextElement): c is CodeSelection { + return (c.type === 'code_piece' || c.type === 'flow_module_code_piece') && c.source !== undefined +} + +export function createCodeSelection( + source: CodeSource, + selection: Pick<CodePieceElement, 'content' | 'startLine' | 'endLine' | 'lang'> +): CodeSelection { + const lines = `L${selection.startLine}-L${selection.endLine}` + if (source.kind === 'flow' && source.part) { + return { + ...selection, + type: 'flow_module_code_piece', + id: source.part, + title: `${source.part} ${lines}`, + value: { type: 'rawscript', language: selection.lang }, + source + } + } + const name = source.part ?? source.path.split('/').pop() + return { + ...selection, + type: 'code_piece', + // A new item is stored under a generated name, which says nothing on a chip. + title: !name || name.startsWith('draft_') ? lines : `${name} ${lines}`, + source + } +} + +/** Whether two selections are of the same lines, whatever code is on them. */ +export function isSameCodeRange(a: CodeSelection, b: CodeSelection): boolean { + return ( + a.source.kind === b.source.kind && + a.source.path === b.source.path && + a.source.part === b.source.part && + a.startLine === b.startLine && + a.endLine === b.endLine + ) +} + /** App frontend file context element */ export interface AppFrontendFileElement { type: 'app_frontend_file' @@ -415,7 +471,13 @@ export type ContextElement = ( // elements), so identify them by (appPath, selector) — keying or removing by // title would collide, giving repeated chips one Svelte key and deleting them // together. Other context types stay identified by (type, title). +// Code selections neither: the same lines of two scripts read alike, and one queued +// before an edit must not stand in for one taken after it. export function contextElementKey(c: ContextElement): string { + if (isCodeSelection(c)) { + const { kind, path, part } = c.source + return `code:${kind}:${path}:${part ?? ''}:${c.startLine}-${c.endLine}:${c.content}` + } return c.type === 'app_dom_selector' ? `dom:${c.appPath}:${c.selector}` : `${c.type}:${c.title}` } @@ -446,10 +508,21 @@ export function isMentionContext(c: ContextElement): c is MentionContext { ) } +/** What the user pointed at for one message, a preview element or selected code. It leaves + * the composer with that message. */ +export type PickContext = AppDomSelectorElement | CodeSelection + +export function isPickContext(c: ContextElement): c is PickContext & { deletable?: boolean } { + return c.type === 'app_dom_selector' || isCodeSelection(c) +} + export function isSameContextElement(a: ContextElement, b: ContextElement): boolean { if (a.type !== b.type) return false if (a.type === 'app_dom_selector' && b.type === 'app_dom_selector') { return a.selector === b.selector && a.appPath === b.appPath } + if (isCodeSelection(a) && isCodeSelection(b)) { + return isSameCodeRange(a, b) && a.content === b.content + } return a.title === b.title } diff --git a/frontend/src/lib/components/copilot/chat/files/AttachedFilesBar.svelte b/frontend/src/lib/components/copilot/chat/files/AttachedFilesBar.svelte index ec52c90ab9..31fb2db9db 100644 --- a/frontend/src/lib/components/copilot/chat/files/AttachedFilesBar.svelte +++ b/frontend/src/lib/components/copilot/chat/files/AttachedFilesBar.svelte @@ -36,7 +36,17 @@ {#snippet chip(card: Card)} {#if card.kind === 'folder'} - <AttachedFolderChip folder={card.folder} onRemove={() => removeCard(card)} /> + <AttachedFolderChip + folder={card.folder} + onRemove={() => removeCard(card)} + onOpenImage={aiChatManager.openImage + ? (f) => + aiChatManager.openImage?.( + { kind: 'file', name: f.name }, + f.name.split('/').pop() || f.name + ) + : undefined} + /> {:else} <AttachedFileChip file={card.file} onRemove={() => removeCard(card)} /> {/if} diff --git a/frontend/src/lib/components/copilot/chat/files/AttachedFolderChip.svelte b/frontend/src/lib/components/copilot/chat/files/AttachedFolderChip.svelte index 068447a878..c13150a206 100644 --- a/frontend/src/lib/components/copilot/chat/files/AttachedFolderChip.svelte +++ b/frontend/src/lib/components/copilot/chat/files/AttachedFolderChip.svelte @@ -1,28 +1,52 @@ <script lang="ts"> import { Folder, X, Loader2, AlertTriangle, Lock } from 'lucide-svelte' - import type { AttachedFolder } from './attachedFiles.svelte' + import Popover from '$lib/components/meltComponents/Popover.svelte' + import { Button } from '$lib/components/common' + import { getFileIcon } from '$lib/components/icons/fileIcon' + import type { AttachedFile, AttachedFolder } from './attachedFiles.svelte' + import { isViewableImageName } from './imageFiles' - let { folder, onRemove }: { folder: AttachedFolder; onRemove: () => void } = $props() + let { + folder, + onRemove, + onOpenImage + }: { + folder: AttachedFolder + onRemove: () => void + /** Shows an image of the folder beside the chat; without it images are listed only. */ + onOpenImage?: (file: AttachedFile) => void + } = $props() let showDelete = $state(false) + let popover: Popover | undefined = $state(undefined) - // Native tooltip listing the contained files (capped). - let hoverList = $derived.by(() => { - if (folder.status === 'locked') return `${folder.name}/ — locked, click send to restore` - if (folder.status === 'unavailable') return `${folder.name}/ — unavailable` - const max = 20 - const shown = folder.files.slice(0, max).map((f) => f.name) - if (folder.files.length > max) shown.push(`… +${folder.files.length - max} more`) - return `${folder.name}/\n${shown.join('\n')}` - }) + // The list renders every row; past this a folder is a build output, not something to browse. + const MAX_LISTED = 300 + + const sorted = $derived( + [...folder.files].sort((a, b) => (a.relPath ?? a.name).localeCompare(b.relPath ?? b.name)) + ) + const imageCount = $derived(folder.files.filter((f) => isOpenable(f)).length) + + function isOpenable(f: AttachedFile): boolean { + return f.status === 'ready' && isViewableImageName(f.sourceName ?? f.name) + } + + /** Path inside the folder: the folder's own name is the chip's label already. */ + function innerPath(f: AttachedFile): string { + const path = f.relPath ?? f.name + const prefix = `${folder.name}/` + return path.startsWith(prefix) ? path.slice(prefix.length) : path + } + + const canList = $derived(folder.status !== 'locked' && folder.status !== 'unavailable') </script> <div - class="border rounded-md px-1 py-0.5 flex flex-row items-center gap-1 text-primary text-xs font-normal cursor-default hover:bg-surface-hover hover:cursor-pointer max-w-48 bg-surface" + class="border rounded-md px-1 py-0.5 flex flex-row items-center gap-1 text-primary text-xs font-normal cursor-default hover:bg-surface-hover max-w-48 bg-surface" onmouseenter={() => (showDelete = true)} onmouseleave={() => (showDelete = false)} role="listitem" - title={hoverList} > <button class="shrink-0" @@ -44,5 +68,70 @@ <Folder size={16} class="text-tertiary" /> {/if} </button> - <span class="truncate" title={folder.name}>{folder.name}</span> + {#if canList} + <Popover bind:this={popover} placement="top-start" class="min-w-0" contentClasses="p-0"> + {#snippet trigger()} + <span class="block truncate cursor-pointer" title={`Show the files in ${folder.name}`} + >{folder.name}</span + > + {/snippet} + {#snippet content()} + <div class="flex flex-col w-72 max-w-[80vw]"> + <div class="px-3 py-2 border-b border-border-light text-2xs text-secondary"> + <span class="font-semibold text-emphasis">{folder.name}/</span> + · {folder.files.length} + {folder.files.length === 1 ? 'file' : 'files'}{imageCount > 0 + ? ` · ${imageCount} ${imageCount === 1 ? 'image' : 'images'}` + : ''} + </div> + <ul class="max-h-72 overflow-y-auto py-1" aria-label={`Files in ${folder.name}`}> + {#each sorted.slice(0, MAX_LISTED) as f (f.name)} + {@const icon = getFileIcon(f.name)} + {@const Icon = icon.icon} + <li> + {#if onOpenImage && isOpenable(f)} + <Button + variant="subtle" + unifiedSize="sm" + wrapperClasses="w-full" + btnClasses="w-full !justify-start rounded-none font-normal" + title={`Open ${innerPath(f)} in the preview`} + onClick={() => { + onOpenImage(f) + popover?.close() + }} + > + <Icon size={14} class="shrink-0 {icon.className ?? ''}" /> + <span class="truncate">{innerPath(f)}</span> + </Button> + {:else} + <div + class="flex items-center gap-2 px-3 py-1 text-xs text-secondary" + title={innerPath(f)} + > + <Icon size={14} class="shrink-0 {icon.className ?? ''}" /> + <span class="truncate">{innerPath(f)}</span> + </div> + {/if} + </li> + {:else} + <li class="px-3 py-1 text-xs text-tertiary">No files linked from this folder.</li> + {/each} + {#if sorted.length > MAX_LISTED} + <li class="px-3 py-1 text-2xs text-tertiary"> + … {sorted.length - MAX_LISTED} more + </li> + {/if} + </ul> + </div> + {/snippet} + </Popover> + {:else} + <span + class="truncate" + title={folder.status === 'locked' + ? `${folder.name}/ — locked, click send to restore` + : `${folder.name}/ — unavailable`}>{folder.name}</span + > + {/if} </div> diff --git a/frontend/src/lib/components/copilot/chat/files/attachedFiles.svelte.ts b/frontend/src/lib/components/copilot/chat/files/attachedFiles.svelte.ts index 6a4b93ee94..4dc0acdef8 100644 --- a/frontend/src/lib/components/copilot/chat/files/attachedFiles.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/files/attachedFiles.svelte.ts @@ -26,6 +26,7 @@ import { } from './attachedFilesDB' import { sanitizeAttachmentName } from '../textFileUtils' import { enumerateDir, isIgnoredPath, queryReadPermission, requestReadPermission } from './fsAccess' +import { isRasterImageName } from './imageFiles' export type AttachedFileStatus = 'indexing' | 'ready' | 'error' | 'locked' | 'unavailable' @@ -59,6 +60,9 @@ export interface AttachedFile extends FileEntry { * sanitize identically are different files even with equal stats. Falls back * to `name` for rows persisted before provenance existed. */ sourceName?: string + /** A binary image (png, jpeg, …): kept so the session's preview can show it, but + * never line-indexed and never handed to the text tools. */ + image?: boolean } /** A linked folder as a first-class object — consumers read this instead of re-grouping rows. */ @@ -128,8 +132,9 @@ export class AttachedFilesStore { return undefined } readyFiles(): AttachedFile[] { - // Folder-root placeholders aren't real files — never expose them to the read/search tools. - return this.files.filter((f) => f.status === 'ready' && !f.isFolderRoot) + // Folder-root placeholders aren't real files and images have no lines — never expose + // either to the read/search tools. + return this.files.filter((f) => f.status === 'ready' && !f.isFolderRoot && !f.image) } get count(): number { return this.files.length @@ -259,7 +264,7 @@ export class AttachedFilesStore { continue // silent no-op on re-link } - const reason = await this.#preflight(file) + const reason = await this.#preflight(file, rawPath) if (reason) { result.rejected.push({ name: sanitizeAttachmentName(rawPath), reason }) continue @@ -315,7 +320,7 @@ export class AttachedFilesStore { const files = await enumerateDir(dirHandle) const sourceId = createLongHash() for (const { file, path } of files) { - if (!(await this.#sniffText(file))) { + if (!(await this.#admissible(file, path))) { result.rejected.push({ name: path, reason: 'Not a text file' }) continue } @@ -497,11 +502,16 @@ export class AttachedFilesStore { } /** Returns a rejection reason, or undefined if the file may be linked. */ - async #preflight(file: File): Promise<string | undefined> { - if (!(await this.#sniffText(file))) return 'Not a text file' + async #preflight(file: File, rawPath: string): Promise<string | undefined> { + if (!(await this.#admissible(file, rawPath))) return 'Not a text file' return undefined } + /** A file the store links: text, or a binary image by its name. */ + async #admissible(file: Blob, path: string): Promise<boolean> { + return isRasterImageName(path) || (await this.#sniffText(file)) + } + async #sniffText(file: Blob): Promise<boolean> { try { return await isTextFile(file) @@ -521,6 +531,9 @@ export class AttachedFilesStore { messageScoped?: boolean id?: string }): void { + // Message rows are decoded text by construction; every other row is judged by + // the name it had on disk. + const image = !p.messageScoped && isRasterImageName(p.sourceName ?? p.name) this.files = [ ...this.files, { @@ -530,7 +543,8 @@ export class AttachedFilesStore { size: p.file.size, lineIndex: [], lineCount: 0, - status: 'indexing', + status: image ? 'ready' : 'indexing', + image: image || undefined, folder: p.folder, sourceId: p.sourceId, handle: p.handle, @@ -539,7 +553,7 @@ export class AttachedFilesStore { id: p.id } ] - void this.#indexFile(p.name, p.file) + if (!image) void this.#indexFile(p.name, p.file) } #pushPlaceholder( @@ -576,7 +590,7 @@ export class AttachedFilesStore { const folder = dirHandle.name const children = await enumerateDir(dirHandle) for (const { file, path } of children) { - if (!(await this.#sniffText(file))) continue + if (!(await this.#admissible(file, path))) continue const name = this.#claimName(path) this.#pushIndexing({ name, @@ -632,7 +646,7 @@ export class AttachedFilesStore { const cur = existing.get(path) if (!cur) { // newly added on disk - if (!(await this.#sniffText(file))) continue + if (!(await this.#admissible(file, path))) continue const name = this.#claimName(path) this.#pushIndexing({ name, @@ -649,9 +663,11 @@ export class AttachedFilesStore { // content changed → re-read + re-index. Patch by row identity — a // message attachment may share the display name. this.files = this.files.map((f) => - f === cur ? { ...f, file, size: file.size, status: 'indexing' } : f + f === cur + ? { ...f, file, size: file.size, status: cur.image ? 'ready' : 'indexing' } + : f ) - void this.#indexFile(cur.name, file) + if (!cur.image) void this.#indexFile(cur.name, file) } } } diff --git a/frontend/src/lib/components/copilot/chat/files/attachedFiles.test.ts b/frontend/src/lib/components/copilot/chat/files/attachedFiles.test.ts index 4376314c5f..dc8c27f2ba 100644 --- a/frontend/src/lib/components/copilot/chat/files/attachedFiles.test.ts +++ b/frontend/src/lib/components/copilot/chat/files/attachedFiles.test.ts @@ -93,6 +93,20 @@ describe('AttachedFilesStore', () => { expect(store.get('proj/app.ts')?.folder).toBe('proj') }) + it('links a folder image as a ready image row, kept out of the text files', async () => { + const png = new File([new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0, 0, 0])], 'logo.png', { + type: 'image/png' + }) + enumerateDirMock.mockResolvedValue([ + { file: file('app.ts', 'x\n'), path: 'proj/app.ts' }, + { file: png, path: 'proj/logo.png' } + ]) + await store.addFolder(dir) + await settle(store) + expect(store.get('proj/logo.png')).toMatchObject({ status: 'ready', image: true }) + expect(store.readyFiles().map((f) => f.name)).toEqual(['proj/app.ts']) + }) + it('refreshFolders detects rename, add, edit, and delete', async () => { enumerateDirMock.mockResolvedValue([ { file: file('app.ts', 'x\n', 1), path: 'proj/app.ts' }, diff --git a/frontend/src/lib/components/copilot/chat/files/fileTools.test.ts b/frontend/src/lib/components/copilot/chat/files/fileTools.test.ts index bb61f95c8c..1cb687842d 100644 --- a/frontend/src/lib/components/copilot/chat/files/fileTools.test.ts +++ b/frontend/src/lib/components/copilot/chat/files/fileTools.test.ts @@ -6,7 +6,7 @@ vi.mock('../shared', () => ({ createToolDef: (_schema: unknown, name: string, description: string) => ({ name, description }) })) -import { searchFilesTool } from './fileTools' +import { imagesAtPath, resultImages, searchFilesTool } from './fileTools' import type { AttachedFile, AttachedFilesStore } from './attachedFiles.svelte' /** Minimal store stub mirroring the real lookup contract (id first, then @@ -58,6 +58,23 @@ describe('search_files — attachments present but nothing readable', () => { expect(msg).toMatch(/re-link/i) }) + it('reports an image row by its status until it is ready', async () => { + const gone = await runSearch( + fakeStore([{ name: 'a.png', status: 'unavailable', image: true }]), + { + pattern: 'x', + file: 'a.png' + } + ) + expect(gone).toMatch(/re-link/i) + const ready = await runSearch(fakeStore([{ name: 'a.png', status: 'ready', image: true }]), { + pattern: 'x', + file: 'a.png' + }) + expect(ready).toMatch(/is an image/i) + expect(ready).not.toMatch(/show_image/) + }) + it('still reports indexing while a file is genuinely indexing', async () => { const msg = await runSearch(fakeStore([{ name: 'a.txt', status: 'indexing' }])) expect(msg).toMatch(/still being indexed/i) @@ -122,3 +139,54 @@ describe('search_files — colliding display names', () => { expect(out).not.toContain('alpha target') }) }) + +describe('resultImages', () => { + it('finds the image a result holds and each render_all item, by its path', () => { + expect(resultImages({ png: 'AAA' })).toEqual([{ format: 'png', path: [] }]) + expect(resultImages({ jpeg: { content: 'AAA' } })).toEqual([{ format: 'jpeg', path: [] }]) + expect( + resultImages({ render_all: [{ markdown: '# a' }, { png: 'AAA' }, { gif: 'BBB' }] }) + ).toEqual([ + { format: 'png', path: ['render_all', 1] }, + { format: 'gif', path: ['render_all', 2] } + ]) + expect(resultImages({ s3: 'charts/a.png' })).toEqual([{ s3: { s3: 'charts/a.png' } }]) + expect(resultImages('s3://secondary/b.jpg')).toEqual([ + { s3: { s3: 'b.jpg', storage: 'secondary' } } + ]) + expect(resultImages([{ s3: 'a.png' }, { s3: 'b.webp' }])).toHaveLength(2) + expect(resultImages([{ s3: 'plot.png' }, { s3: 'data.csv' }])).toEqual([ + { s3: { s3: 'plot.png' } } + ]) + expect(resultImages([{ s3: 'plot.png' }, 'other'])).toEqual([]) + expect(resultImages({ s3: 'data.parquet' })).toEqual([]) + expect(resultImages({ png: 42 })).toEqual([]) + expect(resultImages('png')).toEqual([]) + }) +}) + +describe('imagesAtPath', () => { + // A list of inline images, which resultImages alone does not open. + const result = { charts: [{ png: 'AAA' }, { jpeg: { content: 'BBB' } }], files: ['s3://x/c.png'] } + + it('opens the image a path points at, by its object or its base64 field', () => { + expect(imagesAtPath(result, ['charts', 1])).toEqual([{ format: 'jpeg', path: ['charts', 1] }]) + expect(imagesAtPath(result, ['charts', 0, 'png'])).toEqual([ + { format: 'png', path: ['charts', 0] } + ]) + expect(imagesAtPath(result, ['files', 0])).toEqual([{ s3: { s3: 'c.png', storage: 'x' } }]) + }) + + it('opens the format a path names when the object holds several', () => { + expect(imagesAtPath({ png: 'AAA', jpeg: 'BBB' }, ['jpeg'])).toEqual([ + { format: 'jpeg', path: [] } + ]) + expect(imagesAtPath({ png: 'AAA' }, ['jpeg'])).toEqual([]) + }) + + it('finds nothing where the path leads off the result', () => { + expect(imagesAtPath(result, ['charts', 5])).toEqual([]) + expect(imagesAtPath(result, ['charts', 0, 'png', 'deeper'])).toEqual([]) + expect(imagesAtPath('text', [0])).toEqual([]) + }) +}) diff --git a/frontend/src/lib/components/copilot/chat/files/fileTools.ts b/frontend/src/lib/components/copilot/chat/files/fileTools.ts index d9b1f89e44..897661047b 100644 --- a/frontend/src/lib/components/copilot/chat/files/fileTools.ts +++ b/frontend/src/lib/components/copilot/chat/files/fileTools.ts @@ -19,10 +19,24 @@ import { } from './fileEngine' import type { AttachedFile, AttachedFilesStore } from './attachedFiles.svelte' import { sanitizeAttachmentName } from '../textFileUtils' +import { isViewableImageName } from './imageFiles' +import type { + ImageResultFormat, + ImageSource, + ResultPath +} from '$lib/components/sessions/previewRouter' +import { JobService } from '$lib/gen' +import { workspaceStore } from '$lib/stores' +import { get } from 'svelte/store' +import { isS3ImageKey, parseS3Object, s3ImagePreviewUrl } from '$lib/utils' /** Slice of the GLOBAL tool helpers that exposes the attached-files store. */ export interface AttachedFilesHelper { attachedFiles?: AttachedFilesStore + /** Session chats only: shows an image in the side-panel preview. */ + openImage?: (source: ImageSource, label: string) => void + /** The session's own (possibly forked) workspace, where its jobs run. */ + operatingWorkspace?: string } function storeFrom(helpers: unknown): AttachedFilesStore | undefined { @@ -35,9 +49,19 @@ function storeFrom(helpers: unknown): AttachedFilesStore | undefined { * or undefined when it's `ready`. Shared by read_file and search_files so both report the * same accurate status instead of search_files claiming a non-ready file isn't attached. */ -function notReadyMessage(store: AttachedFilesStore, file: string): string | undefined { +function notReadyMessage( + store: AttachedFilesStore, + file: string, + helpers: unknown +): string | undefined { const entry = store.resolve(file) - if (entry?.status === 'ready') return undefined + if (entry?.status === 'ready') { + if (!entry.image) return undefined + // show_image exists only where an image can open: a session's preview panel. + return (helpers as AttachedFilesHelper | undefined)?.openImage + ? `"${file}" is an image, which has no text to read or search. Show it to the user with show_image.` + : `"${file}" is an image, which has no text to read or search.` + } if (entry?.status === 'indexing') return `File "${file}" is still being indexed. Try again shortly.` if (entry?.status === 'locked') @@ -110,7 +134,7 @@ export const searchFilesTool: SessionTool<{}> = { // Validate a specifically requested file against the full store first, so a non-ready // target reports its real status (indexing/locked/…) instead of "not attached". if (parsed.file) { - const notReady = notReadyMessage(store, parsed.file) + const notReady = notReadyMessage(store, parsed.file, helpers) if (notReady) return notReady } // Restrict to the resolved row itself, not a name filter: display names may @@ -178,7 +202,7 @@ export const readFileTool: SessionTool<{}> = { return 'No files are attached to this conversation.' } const parsed = readFileSchema.parse(args) - const notReady = notReadyMessage(store, parsed.file) + const notReady = notReadyMessage(store, parsed.file, helpers) if (notReady) return notReady const entry = store.resolve(parsed.file)! toolCallbacks.setToolStatus(toolId, { content: `Reading "${entry.name}"...` }) @@ -198,7 +222,205 @@ export const readFileTool: SessionTool<{}> = { } } -export const fileTools: SessionTool<{}>[] = [searchFilesTool, readFileTool] +const showImageSchema = z.object({ + file: z + .string() + .optional() + .describe('Exact filename of an attached image, as the roster lists it.'), + job_id: z + .string() + .optional() + .describe('A completed job whose result holds images (a run, a flow).'), + step_id: z + .string() + .optional() + .describe('With job_id on a flow: the step whose result holds the image, by its id.'), + path: z + .array(z.union([z.string(), z.number()])) + .optional() + .describe( + 'With job_id: keys and list indexes from the root of the result (of the step, with step_id) to the image, e.g. [2] or ["charts", 0, "png"]. Without it, every image the result holds is shown.' + ), + s3: z + .object({ + s3: z.string().describe('The object key, e.g. "charts/plot.png".'), + storage: z + .string() + .optional() + .describe('The secondary storage holding it, when not the workspace default.') + }) + .optional() + .describe('An S3 image object, as a result holds it: `{ s3, storage? }`.') +}) + +const showImageToolDef = createToolDef( + showImageSchema, + 'show_image', + 'Show an image to the user in the side-panel preview next to the chat, where they can zoom and pan it. Pass exactly one of: `file` for an image the user attached (png, jpeg, gif, webp, avif, bmp, ico or svg); `job_id` (and `step_id` for a flow step) for a job result, showing every image it holds (inline png, jpeg or gif, S3 image objects, each `render_all` item), or with `path` only the image at that place in the result, read with get_run first; or `s3` for an S3 image object. Call it again to show more images. You cannot see the image yourself: this only displays it to the user.' +) + +const RESULT_IMAGE_FORMATS: ImageResultFormat[] = ['png', 'jpeg', 'gif'] + +export type ResultImage = + | { format: ImageResultFormat; path: ResultPath } + | { s3: { s3: string; storage?: string } } + +function s3Image(value: unknown): ResultImage | undefined { + if (typeof value === 'string') { + if (!/^s3:\/\/[^/]*\/.+/.test(value)) return undefined + } else if (typeof (value as { s3?: unknown } | undefined)?.s3 !== 'string') return undefined + const s3 = parseS3Object(value as Parameters<typeof parseS3Object>[0]) + return isS3ImageKey(s3.s3) ? { s3: { s3: s3.s3, storage: s3.storage } } : undefined +} + +/** The images a result holds, where DisplayResult renders them: the result's own + * `png`/`jpeg`/`gif` key (a base64 string or `{ content }`), an S3 image object, the images + * among a list of S3 objects (DisplayResult lists any mix of file types), and each + * `render_all` item. */ +export function resultImages(value: unknown, path: ResultPath = []): ResultImage[] { + const s3 = s3Image(value) + if (s3) return [s3] + if (Array.isArray(value)) { + const isS3List = value.every((i) => typeof (i as { s3?: unknown } | null)?.s3 === 'string') + return isS3List ? value.flatMap((i) => s3Image(i) ?? []) : [] + } + if (!value || typeof value !== 'object') return [] + const obj = value as Record<string, unknown> + if (Array.isArray(obj.render_all)) { + return obj.render_all.flatMap((child, i) => resultImages(child, [...path, 'render_all', i])) + } + const format = RESULT_IMAGE_FORMATS.find((f) => { + const v = obj[f] + return typeof v === 'string' || typeof (v as { content?: unknown })?.content === 'string' + }) + return format ? [{ format, path }] : [] +} + +/** The images at `path` inside a result. A path may end on the image's base64 field + * (`[0, "png"]`), which names the same image as the object holding it. */ +export function imagesAtPath(result: unknown, path: ResultPath): ResultImage[] { + const last = path.at(-1) + const format = RESULT_IMAGE_FORMATS.find((f) => f === last) + const at = format ? path.slice(0, -1) : path + let value = result + for (const key of at) { + if (!value || typeof value !== 'object') return [] + value = (value as Record<string | number, unknown>)[key] + } + if (format) { + // The named field, not the first image field of the object holding it. + const v = (value as Record<string, unknown> | undefined)?.[format] + const isImage = + typeof v === 'string' || typeof (v as { content?: unknown })?.content === 'string' + return isImage ? [{ format, path: at }] : [] + } + return resultImages(value, at) +} + +async function showResultImages( + openImage: (source: ImageSource, label: string) => void, + workspace: string, + jobId: string, + stepId: string | undefined, + path: ResultPath | undefined +): Promise<string> { + const what = `job ${jobId}${stepId ? ` step ${stepId}` : ''}` + let result: unknown + try { + result = stepId + ? await JobService.resultById({ workspace, flowJobId: jobId, nodeId: stepId }) + : await JobService.getCompletedJobResult({ workspace, id: jobId }) + } catch (e) { + return `Could not load the result of ${what}: ${e instanceof Error ? e.message : String(e)}` + } + const images = path?.length ? imagesAtPath(result, path) : resultImages(result) + if (images.length === 0) { + return path?.length + ? `Nothing at ${JSON.stringify(path)} in the result of ${what} is an image. Read the result with get_run to find the image's path.` + : `The result of ${what} holds no image.` + } + const base = stepId ? `${stepId} result` : `Result ${jobId.slice(-8)}` + for (const image of images) { + if ('s3' in image) { + openImage( + { kind: 'url', url: s3ImagePreviewUrl(workspace, image.s3) }, + image.s3.s3.split('/').pop() || image.s3.s3 + ) + continue + } + const { format, path } = image + const at = path.length ? ` #${path.filter((k) => typeof k === 'number').join('.')}` : '' + openImage( + { + kind: 'result', + workspace, + jobId, + format, + ...(stepId ? { nodeId: stepId } : {}), + ...(path.length ? { path } : {}) + }, + base + at + ) + } + return images.length === 1 + ? 'Showing the result image in the preview panel.' + : `Showing the ${images.length} result images in the preview panel, one tab each.` +} + +export const showImageTool: SessionTool<{}> = { + requires: NONE, + def: showImageToolDef, + planModeSafe: true, + fn: async ({ args, helpers }) => { + const h = helpers as AttachedFilesHelper | undefined + const openImage = h?.openImage + if (!openImage) return 'Images can only be shown inside an AI session.' + const parsed = showImageSchema.parse(args) + const given = [parsed.file, parsed.job_id, parsed.s3].filter((v) => v !== undefined).length + if (given !== 1) { + return 'Pass exactly one of `file` (an attached image), `job_id` (a job result) or `s3` (an S3 image object).' + } + if (!parsed.job_id && (parsed.step_id || parsed.path)) { + return '`step_id` and `path` locate an image in a job result: pass them with `job_id`.' + } + if (parsed.job_id || parsed.s3) { + const workspace = h?.operatingWorkspace ?? get(workspaceStore) + if (!workspace) return 'No workspace to load the image from.' + if (parsed.job_id) { + return showResultImages(openImage, workspace, parsed.job_id, parsed.step_id, parsed.path) + } + const s3 = parsed.s3! + if (!isS3ImageKey(s3.s3)) { + return `"${s3.s3}" is not an image the viewer can show (png, jpeg or webp).` + } + openImage( + { kind: 'url', url: s3ImagePreviewUrl(workspace, s3) }, + s3.s3.split('/').pop() || s3.s3 + ) + return `Showing "${s3.s3}" in the preview panel.` + } + if (!parsed.file) return 'Pass `file` for an attached image or `job_id` for a job result.' + const store = storeFrom(helpers) + if (!store) return 'No files are attached to this chat.' + const entry = store.resolve(parsed.file) + if (!entry || entry.messageScoped || entry.isFolderRoot) { + return ( + notReadyMessage(store, parsed.file, helpers) ?? + `No attached file matching "${parsed.file}".` + ) + } + if (!isViewableImageName(entry.sourceName ?? entry.name)) { + return `"${entry.name}" is not an image. Read it with read_file instead.` + } + if (entry.status !== 'ready') { + return notReadyMessage(store, parsed.file, helpers) ?? `"${entry.name}" is not available.` + } + openImage({ kind: 'file', name: entry.name }, entry.name.split('/').pop() || entry.name) + return `Showing "${entry.name}" in the preview panel.` + } +} + +export const fileTools: SessionTool<{}>[] = [searchFilesTool, readFileTool, showImageTool] function rosterLine(f: AttachedFile): string { // Message rows are addressed by their stable id (names may collide); session @@ -211,6 +433,7 @@ function rosterLine(f: AttachedFile): string { if (f.status === 'locked') return `- ${ref} (locked — needs the user to restore access)` if (f.status === 'unavailable') return `- ${ref} (unavailable)` if (f.status === 'error') return `- ${ref} (failed to load)` + if (f.image) return `- ${ref} — image, ${humanSize(f.size)}` return `- ${ref} — ${f.lineCount} lines, ${humanSize(f.size)}` } @@ -253,6 +476,9 @@ export function buildAttachedFilesRoster( '## Attached files', 'The user has attached the following files to this conversation. Their contents are NOT included here.', 'Use the `search_files` tool to find content with a regex, and `read_file` to read a bounded window of lines.', + ...([...store.folders.flatMap((d) => d.files), ...store.standalone].some((f) => f.image) + ? ['Images have no text: `show_image` displays one to the user, where it is available.'] + : []), 'Reference a file by its file id when one is shown, otherwise by its filename.', '', lines.join('\n') diff --git a/frontend/src/lib/components/copilot/chat/files/imageFiles.ts b/frontend/src/lib/components/copilot/chat/files/imageFiles.ts new file mode 100644 index 0000000000..1d8b832116 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/files/imageFiles.ts @@ -0,0 +1,72 @@ +/** + * Which linked files the session's image viewer can show. Decided by extension: a + * folder's files come off disk through the File System Access API, which leaves + * `File.type` empty for many of them, and a snapshot Blob restored from IndexedDB + * keeps whatever type it had at link time. + */ + +/** Binary image formats: linked as image rows, never line-indexed or read as text. */ +const RASTER_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'avif', 'bmp', 'ico']) + +function extensionOf(name: string): string { + const dot = name.lastIndexOf('.') + return dot >= 0 ? name.slice(dot + 1).toLowerCase() : '' +} + +/** A binary image the store keeps as an image row instead of rejecting it as non-text. */ +export function isRasterImageName(name: string): boolean { + return RASTER_EXTENSIONS.has(extensionOf(name)) +} + +/** Whether the image viewer can show the file. SVG is text, so it stays readable by the + * file tools as well. */ +export function isViewableImageName(name: string): boolean { + return isRasterImageName(name) || extensionOf(name) === 'svg' +} + +const MIME_BY_EXTENSION: Record<string, string> = { + png: 'image/png', + jpg: 'image/jpeg', + jpeg: 'image/jpeg', + gif: 'image/gif', + webp: 'image/webp', + avif: 'image/avif', + bmp: 'image/bmp', + ico: 'image/x-icon', + svg: 'image/svg+xml' +} + +/** The bytes as a Blob the browser decodes as an image. An SVG served without + * `image/svg+xml` does not render in an `<img>`, and a folder file often has no type. */ +export function asImageBlob(file: Blob, name: string): Blob { + const type = MIME_BY_EXTENSION[extensionOf(name)] + if (!type || file.type === type) return file + return new Blob([file], { type }) +} + +/** + * Stable short key for an image sent in a chat message, which has no id of its own: + * FNV-1a over the data URL, plus its length. A tab persists this key and finds the + * image again by recomputing it over the transcript's images. + */ +export function imageContentKey(dataUrl: string, owner?: object): string { + // An image tab re-resolves on every transcript change, so it passes the message or + // image object as `owner`: the hash is then computed once per image and released with it. + if (!owner) return fnv1a(dataUrl) + const hit = keyByOwner.get(owner) + if (hit?.dataUrl === dataUrl) return hit.key + const key = fnv1a(dataUrl) + keyByOwner.set(owner, { dataUrl, key }) + return key +} + +const keyByOwner = new WeakMap<object, { dataUrl: string; key: string }>() + +function fnv1a(dataUrl: string): string { + let h = 0x811c9dc5 + for (let i = 0; i < dataUrl.length; i++) { + h ^= dataUrl.charCodeAt(i) + h = Math.imul(h, 0x01000193) + } + return `${(h >>> 0).toString(16)}-${dataUrl.length.toString(36)}` +} diff --git a/frontend/src/lib/components/copilot/chat/flow/core.ts b/frontend/src/lib/components/copilot/chat/flow/core.ts index 2dd6f16526..1d64dfebae 100644 --- a/frontend/src/lib/components/copilot/chat/flow/core.ts +++ b/frontend/src/lib/components/copilot/chat/flow/core.ts @@ -19,7 +19,6 @@ import { buildSchemaForTool, buildTestRunArgs, buildContextString, - applyCodePiecesToFlowModules, SPECIAL_MODULE_IDS, formatScriptLintResult, type ScriptLintResult, @@ -42,7 +41,7 @@ import { import { flowModuleSchema } from './openFlowZod.gen' import { collectAllFlowModuleIdsFromModules } from '$lib/components/flows/flowTree' import { - buildEditableFlowJson as buildEditableFlowJsonBase, + buildEditableFlowJson, FLOW_VALUE_SETTINGS_KEYS, pickFlowValueSettings, validateEditableFlowJson, @@ -77,27 +76,6 @@ function formatEmptyInlineScriptWarning({ return ` Warning: inline scripts ${moduleList} are empty for now. Use set_module_code to fill them in.` } -/** - * Build the agent-facing compact view of a flow, with editor-only post-processing - * (insert `[#START]` / `[#END]` markers around code pieces selected as context). - * Delegates to the shared `buildEditableFlowJson` for the rest. - */ -function buildEditableFlowJson( - flow: ExtendedOpenFlow, - inlineScriptSession?: InlineScriptSession, - selectedContext: ContextElement[] = [] -): EditableFlowJson { - const json = buildEditableFlowJsonBase( - { value: flow.value, schema: flow.schema }, - inlineScriptSession - ) - const codePieces = selectedContext.filter((c) => c.type === 'flow_module_code_piece') - if (codePieces.length === 0) { - return json - } - return { ...json, modules: applyCodePiecesToFlowModules(codePieces, json.modules) } -} - /** * Helper interface for AI chat flow operations * @@ -567,7 +545,9 @@ export const flowTools: Tool<FlowAIChatHelpers>[] = [ // Snapshot the current flow with a fresh session so the compact JSON matches what the model saw, // then copy extracted inline scripts back into the helper session before applying the patch. const inlineScriptSession = createInlineScriptSession() - const currentFlowJson = JSON.stringify(buildEditableFlowJson(flow, inlineScriptSession)) + const currentFlowJson = JSON.stringify( + buildEditableFlowJson({ value: flow.value, schema: flow.schema }, inlineScriptSession) + ) toolCallbacks.setToolStatus(toolId, { content: 'Applying JSON patch...' @@ -1230,7 +1210,10 @@ ${instructions}` // Clear the inline script store and extract inline scripts for token optimization scriptSession?.clear() - const editableFlowJson = buildEditableFlowJson(flow, scriptSession, selectedContext) + const editableFlowJson = buildEditableFlowJson( + { value: flow.value, schema: flow.schema }, + scriptSession + ) let flowContent = `## CURRENT FLOW JSON COMPACT: \`\`\`json diff --git a/frontend/src/lib/components/copilot/chat/flow/openFlow.json b/frontend/src/lib/components/copilot/chat/flow/openFlow.json index 636fe7589e..af6de17833 100644 --- a/frontend/src/lib/components/copilot/chat/flow/openFlow.json +++ b/frontend/src/lib/components/copilot/chat/flow/openFlow.json @@ -1 +1 @@ -{"openapi":"3.0.3","info":{"version":"1.880.1","title":"OpenFlow Spec","contact":{"name":"Ruben Fiszel","email":"ruben@windmill.dev","url":"https://windmill.dev"},"license":{"name":"Apache 2.0","url":"https://www.apache.org/licenses/LICENSE-2.0.html"}},"paths":{},"externalDocs":{"description":"documentation portal","url":"https://windmill.dev"},"components":{"schemas":{"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-<type>' (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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this flow does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed, like any failed step."},"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"},"timeout":{"type":"integer","description":"Wall-clock limit in seconds for the whole flow run, counted from its start and including time spent sleeping or suspended at an approval. It also applies when the flow is called as a subflow step, unless that step sets its own timeout, which replaces it. It is checked periodically, so a run can go a few seconds past it. When it expires, the running steps are cancelled, the failure module runs if there is one, and the flow ends cancelled with a timeout error. A calling flow sees the subflow step fail with that error."},"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 × 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 × 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 — 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.<step_id>'"}},"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"},"preview_only":{"type":"boolean","description":"If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run."}}},"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/<flow_path>-<step_id>"},"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"}},"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"}},"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"}},"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"}},"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"}},"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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this step does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed."},"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",null]},"alt_access_type":{"type":"string","nullable":true,"description":"Alternative access level","enum":["r","w","rw",null]}}}}},"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')"},"tag_override":{"type":"string","description":"Override the subflow's worker group tag. Its steps run on this tag unless the subflow sets preserve_step_tags"},"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"},"iteration_label":{"description":"Optional expression evaluated once per iteration into the label the run viewers show for it, e.g. 'flow_input.iter.value.name'. It can reference 'flow_input.iter' and 'results'. Purely informational, a failing expression leaves the iteration unlabelled and never fails it. Labels are capped at 100 characters","$ref":"#/components/schemas/InputTransform"}},"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.<its_own_id>' 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"},"max_iterations":{"type":"integer","minimum":1,"description":"Maximum number of iterations. Checked after each iteration; when reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"},"max_duration_secs":{"type":"integer","minimum":1,"description":"Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"}},"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"},"parallelism":{"description":"Maximum number of branches running at once when parallel=true. Can be static number or expression","$ref":"#/components/schemas/InputTransform"}},"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."},"background":{"type":"boolean","description":"Flowmodule tools only. The agent is answered as soon as the tool's job starts and keeps working; the job's result reaches it in a later message. If the agent finishes its answer first, it stops without holding a worker until the job is done, then continues with the result."},"background_after_secs":{"type":"integer","minimum":1,"description":"Flowmodule tools only, with background unset. The agent waits up to this many seconds for the tool's job and gets its result as usual; a job still running then continues as a background one, its result reaching the agent in a later message."},"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"}]},"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 — 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 or Gemini'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: { <question name>: answer },\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\nthe answers, follow it with a branchone whose branch exprs read\nresults.<id>.output.<question>.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"}}}},"continued_on_error":{"type":"array","description":"On a root flow, the steps at any depth that failed and that the flow went past because of continue_on_error (at most 100).","items":{"type":"object","properties":{"id":{"type":"string"},"job":{"type":"string","format":"uuid"}},"required":["id","job"]}},"test_subflows":{"type":"object","description":"In a flow test run, deployed subflow path -> the flow value with the test's step overrides applied, run in place of the deployed subflow.","additionalProperties":{"type":"object"}}},"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_labels":{"type":"array","description":"For a for-loop step whose iteration_label is set, each iteration's label, aligned with flow_jobs. An entry is null when its label evaluated to nothing","items":{"type":"string","nullable":true}},"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","description":"The outcome of each agent action, by position. null while a background tool call is still running.","items":{"type":"boolean","nullable":true}}},"required":["type"]}}}} \ No newline at end of file +{"openapi":"3.0.3","info":{"version":"1.885.0","title":"OpenFlow Spec","contact":{"name":"Ruben Fiszel","email":"ruben@windmill.dev","url":"https://windmill.dev"},"license":{"name":"Apache 2.0","url":"https://www.apache.org/licenses/LICENSE-2.0.html"}},"paths":{},"externalDocs":{"description":"documentation portal","url":"https://windmill.dev"},"components":{"schemas":{"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-<type>' (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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this flow does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed, like any failed step."},"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"},"timeout":{"type":"integer","description":"Wall-clock limit in seconds for the whole flow run, counted from its start and including time spent sleeping or suspended at an approval. It also applies when the flow is called as a subflow step, unless that step sets its own timeout, which replaces it. It is checked periodically, so a run can go a few seconds past it. When it expires, the running steps are cancelled, the failure module runs if there is one, and the flow ends cancelled with a timeout error. A calling flow sees the subflow step fail with that error."},"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 × 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 × 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 — 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.<step_id>'"}},"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"},"preview_only":{"type":"boolean","description":"If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run."}}},"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"},"show_on_home":{"type":"boolean","description":"If true, a run waiting on this step is listed on the Home page of each user who can approve it. Leave unset when the approval request is sent through another channel (Slack, Discord, email), so it does not sit there unanswered"}}},"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/<flow_path>-<step_id>"},"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"}},"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"}},"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"}},"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"}},"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"}},"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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this step does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed."},"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",null]},"alt_access_type":{"type":"string","nullable":true,"description":"Alternative access level","enum":["r","w","rw",null]}}}}},"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')"},"tag_override":{"type":"string","description":"Override the subflow's worker group tag. Its steps run on this tag unless the subflow sets preserve_step_tags"},"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"},"failure_threshold":{"description":"With skip_failures, the loop fails with an error named 'FailureThresholdReached' as soon as this many iterations have failed. Static number or expression (e.g. 'Math.ceil(flow_input.targets.length * 0.1)' for a percentage), evaluated once when the loop starts. A sequential loop stops at the iteration that reaches it. A parallel loop cancels the iterations no worker has picked up yet, including those held back by parallelism, while iterations already picked up finish; set parallelism to bound how many are in flight when the threshold is reached","$ref":"#/components/schemas/InputTransform"},"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"},"iteration_label":{"description":"Optional expression evaluated once per iteration into the label the run viewers show for it, e.g. 'flow_input.iter.value.name'. It can reference 'flow_input.iter' and 'results'. Purely informational, a failing expression leaves the iteration unlabelled and never fails it. Labels are capped at 100 characters","$ref":"#/components/schemas/InputTransform"}},"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.<its_own_id>' 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"},"max_iterations":{"type":"integer","minimum":1,"description":"Maximum number of iterations. Checked after each iteration; when reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"},"max_duration_secs":{"type":"integer","minimum":1,"description":"Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"},"failure_threshold":{"description":"With skip_failures, the loop fails with an error named 'FailureThresholdReached' at the iteration that brings the failed iterations to this count. Static number or expression, evaluated once when the loop starts","$ref":"#/components/schemas/InputTransform"}},"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"},"parallelism":{"description":"Maximum number of branches running at once when parallel=true. Can be static number or expression","$ref":"#/components/schemas/InputTransform"}},"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."},"background":{"type":"boolean","description":"Flowmodule tools only. The agent is answered as soon as the tool's job starts and keeps working; the job's result reaches it in a later message. If the agent finishes its answer first, it stops without holding a worker until the job is done, then continues with the result."},"background_after_secs":{"type":"integer","minimum":1,"description":"Flowmodule tools only, with background unset. The agent waits up to this many seconds for the tool's job and gets its result as usual; a job still running then continues as a background one, its result reaching the agent in a later message."},"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"}]},"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 — 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 or Gemini'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: { <question name>: answer },\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\nthe answers, follow it with a branchone whose branch exprs read\nresults.<id>.output.<question>.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"}}}},"continued_on_error":{"type":"array","description":"On a root flow, the steps at any depth that failed and that the flow went past because of continue_on_error (at most 100).","items":{"type":"object","properties":{"id":{"type":"string"},"job":{"type":"string","format":"uuid"}},"required":["id","job"]}},"test_subflows":{"type":"object","description":"In a flow test run, deployed subflow path -> the flow value with the test's step overrides applied, run in place of the deployed subflow.","additionalProperties":{"type":"object"}}},"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_labels":{"type":"array","description":"For a for-loop step whose iteration_label is set, each iteration's label, aligned with flow_jobs. An entry is null when its label evaluated to nothing","items":{"type":"string","nullable":true}},"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"},"approved_at":{"type":"string","format":"date-time","description":"absent for approvals recorded before it was kept"},"approved":{"type":"boolean","description":"false for a rejection the flow continued past; absent for approvals recorded before it was kept\n"}},"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","description":"The outcome of each agent action, by position. null while a background tool call is still running.","items":{"type":"boolean","nullable":true}}},"required":["type"]}}}} \ No newline at end of file diff --git a/frontend/src/lib/components/copilot/chat/flow/openFlowZod.gen.ts b/frontend/src/lib/components/copilot/chat/flow/openFlowZod.gen.ts index 8c84735a94..b9ba6f71ed 100644 --- a/frontend/src/lib/components/copilot/chat/flow/openFlowZod.gen.ts +++ b/frontend/src/lib/components/copilot/chat/flow/openFlowZod.gen.ts @@ -1,6 +1,6 @@ import { z } from "zod" -export const flowModuleValueSchema = z.discriminatedUnion("type", [z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments"), "content": z.string().describe("The script source code. Should export a 'main' function"), "language": z.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"]).describe("Programming language for this script"), "path": z.string().describe("Optional path for saving this script").optional(), "lock": z.string().describe("Lock file content for dependencies").optional(), "type": z.literal("rawscript"), "tag": z.string().describe("Worker group tag for execution routing").optional(), "concurrent_limit": z.number().describe("Maximum concurrent executions of this script").optional(), "concurrency_time_window_s": z.number().describe("Time window for concurrent_limit").optional(), "on_concurrency_limit": z.enum(["queue","fail"]).describe("What a run of this step does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed.").optional(), "custom_concurrency_key": z.string().describe("Custom key for grouping concurrent executions").optional(), "is_trigger": z.boolean().describe("If true, this script is a trigger that can start the flow").optional(), "assets": z.array(z.object({ "path": z.string().describe("Path to the asset"), "kind": z.enum(["s3object","resource","ducklake","datatable","volume","dbt"]).describe("Type of asset"), "access_type": z.union([z.literal("r"), z.literal("w"), z.literal("rw"), z.literal(null)]).nullable().describe("Access level for this asset").optional(), "alt_access_type": z.union([z.literal("r"), z.literal("w"), z.literal("rw"), z.literal(null)]).nullable().describe("Alternative access level").optional() })).describe("External resources this script accesses (S3 objects, resources, etc.)").optional() }).describe("Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms"), z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments"), "path": z.string().describe("Path to the script in the workspace (e.g., 'f/scripts/send_email')"), "hash": z.string().describe("Optional specific version hash of the script to use").optional(), "type": z.literal("script"), "tag_override": z.string().describe("Override the script's default worker group tag").optional(), "is_trigger": z.boolean().describe("If true, this script is a trigger that can start the flow").optional() }).describe("Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code"), z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments"), "path": z.string().describe("Path to the flow in the workspace (e.g., 'f/flows/process_user')"), "tag_override": z.string().describe("Override the subflow's worker group tag. Its steps run on this tag unless the subflow sets preserve_step_tags").optional(), "type": z.literal("flow") }).describe("Reference to an existing flow by path. Use this to call another flow as a subflow"), z.object({ "modules": z.array(z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.lazy(() => flowModuleValueSchema), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional(), "preview_only": z.boolean().describe("If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run.").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("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").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("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).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch")).describe("Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'"), "iterator": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs"), "skip_failures": z.boolean().describe("If true, iteration failures don't stop the loop. Failed iterations return null"), "type": z.literal("forloopflow"), "parallel": z.boolean().describe("If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency").optional(), "parallelism": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "squash": z.boolean().optional(), "iteration_label": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional() }).describe("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"), z.object({ "modules": z.array(z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.lazy(() => flowModuleValueSchema), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional(), "preview_only": z.boolean().describe("If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run.").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("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").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("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).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch")).describe("Steps to execute in each iteration"), "skip_failures": z.boolean().describe("If true, iteration failures don't stop the loop. Failed iterations return null"), "type": z.literal("whileloopflow"), "parallel": z.boolean().describe("If true, iterations run concurrently (use with caution in while loops)").optional(), "parallelism": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "squash": z.boolean().optional(), "max_iterations": z.number().int().gte(1).describe("Maximum number of iterations. Checked after each iteration; when reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'").optional(), "max_duration_secs": z.number().int().gte(1).describe("Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'").optional() }).describe("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.<its_own_id>' 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"), z.object({ "branches": z.array(z.object({ "summary": z.string().describe("Short description of this branch condition").optional(), "expr": z.string().describe("JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins"), "modules": z.array(z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.lazy(() => flowModuleValueSchema), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional(), "preview_only": z.boolean().describe("If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run.").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("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").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("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).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch")).describe("Steps to execute if this branch's expr is true") })).describe("Array of branches to evaluate in order. The first branch with expr evaluating to true executes"), "default": z.array(z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.lazy(() => flowModuleValueSchema), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional(), "preview_only": z.boolean().describe("If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run.").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("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").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("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).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch")).describe("Steps to execute if no branch expressions match"), "type": z.literal("branchone") }).describe("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"), z.object({ "branches": z.array(z.object({ "summary": z.string().describe("Short description of this branch's purpose").optional(), "skip_failure": z.boolean().describe("If true, failure in this branch doesn't fail the entire flow").optional(), "modules": z.array(z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.lazy(() => flowModuleValueSchema), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional(), "preview_only": z.boolean().describe("If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run.").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("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").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("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).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch")).describe("Steps to execute in this branch") })).describe("Array of branches that all execute (either in parallel or sequentially)"), "type": z.literal("branchall"), "parallel": z.boolean().describe("If true, all branches execute concurrently. If false, they execute sequentially").optional(), "parallelism": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional() }).describe("Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently"), z.object({ "type": z.literal("identity"), "flow": z.boolean().describe("If true, marks this as a flow identity (special handling)").optional() }).describe("Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder"), z.object({ "input_transforms": z.object({ "provider": z.discriminatedUnion("type", [z.object({ "value": z.object({ "kind": z.enum(["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]).describe("Supported AI provider types"), "resource": z.string().describe("Resource reference in format '$res:{resource_path}' pointing to provider credentials"), "model": z.string().describe("Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"), "reasoning_effort": z.string().describe("Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default.").optional() }).describe("Complete AI provider configuration with resource reference and model selection"), "type": z.literal("static") }).describe("Static provider configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined").optional(), "output_type": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Output format type.\nValid values: 'text' (default) - plain text response, 'image' - image generation\n").optional(), "user_message": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "system_prompt": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("System instructions that guide the AI's behavior, persona, and response style. Optional.").optional(), "streaming": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "memory": z.discriminatedUnion("type", [z.object({ "value": z.discriminatedUnion("kind", [z.object({ "kind": z.literal("off") }).describe("No conversation memory/context"), z.object({ "kind": z.literal("window"), "context_length": z.number().int().describe("Number of most recent messages to load and store. 0 turns memory off.") }).describe("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"), z.object({ "kind": z.literal("compaction"), "context_window": z.number().int().describe("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").optional() }).describe("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"), z.object({ "kind": z.literal("auto"), "context_length": z.number().int().describe("Maximum number of messages to retain in context").optional(), "memory_id": z.string().describe("Identifier for persistent memory across agent invocations").optional() }).describe("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"), z.object({ "kind": z.literal("manual"), "messages": z.array(z.object({ "role": z.enum(["user","assistant","system"]), "content": z.string() }).describe("A single message in conversation history")) }).describe("Deprecated, still read as it was written. Move the step to `off` with `previous_messages` instead.")]).describe("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`."), "type": z.literal("static") }).describe("Static memory configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined").optional(), "memory_id": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "previous_messages": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "output_schema": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "user_attachments": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "enabled_tools": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "max_completion_tokens": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "temperature": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "max_iterations": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Number. Limits how many times the agent can loop through reasoning and tool use.\nRange: 1-1000.\n").optional(), "model": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "reasoning_effort": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional() }).describe("Input parameters for the AI agent mapped to their values"), "tools": z.array(z.object({ "id": z.string().describe("Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')"), "summary": z.string().describe("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'.").optional(), "description": z.string().describe("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.").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("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.").optional(), "requires_approval": z.boolean().describe("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.").optional(), "background": z.boolean().describe("Flowmodule tools only. The agent is answered as soon as the tool's job starts and keeps working; the job's result reaches it in a later message. If the agent finishes its answer first, it stops without holding a worker until the job is done, then continues with the result.").optional(), "background_after_secs": z.number().int().gte(1).describe("Flowmodule tools only, with background unset. The agent waits up to this many seconds for the tool's job and gets its result as usual; a job still running then continues as a background one, its result reaching the agent in a later message.").optional(), "value": z.any().superRefine((x, ctx) => { +export const flowModuleValueSchema = z.discriminatedUnion("type", [z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments"), "content": z.string().describe("The script source code. Should export a 'main' function"), "language": z.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"]).describe("Programming language for this script"), "path": z.string().describe("Optional path for saving this script").optional(), "lock": z.string().describe("Lock file content for dependencies").optional(), "type": z.literal("rawscript"), "tag": z.string().describe("Worker group tag for execution routing").optional(), "concurrent_limit": z.number().describe("Maximum concurrent executions of this script").optional(), "concurrency_time_window_s": z.number().describe("Time window for concurrent_limit").optional(), "on_concurrency_limit": z.enum(["queue","fail"]).describe("What a run of this step does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed.").optional(), "custom_concurrency_key": z.string().describe("Custom key for grouping concurrent executions").optional(), "is_trigger": z.boolean().describe("If true, this script is a trigger that can start the flow").optional(), "assets": z.array(z.object({ "path": z.string().describe("Path to the asset"), "kind": z.enum(["s3object","resource","ducklake","datatable","volume","dbt"]).describe("Type of asset"), "access_type": z.union([z.literal("r"), z.literal("w"), z.literal("rw"), z.literal(null)]).nullable().describe("Access level for this asset").optional(), "alt_access_type": z.union([z.literal("r"), z.literal("w"), z.literal("rw"), z.literal(null)]).nullable().describe("Alternative access level").optional() })).describe("External resources this script accesses (S3 objects, resources, etc.)").optional() }).describe("Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms"), z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments"), "path": z.string().describe("Path to the script in the workspace (e.g., 'f/scripts/send_email')"), "hash": z.string().describe("Optional specific version hash of the script to use").optional(), "type": z.literal("script"), "tag_override": z.string().describe("Override the script's default worker group tag").optional(), "is_trigger": z.boolean().describe("If true, this script is a trigger that can start the flow").optional() }).describe("Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code"), z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments"), "path": z.string().describe("Path to the flow in the workspace (e.g., 'f/flows/process_user')"), "tag_override": z.string().describe("Override the subflow's worker group tag. Its steps run on this tag unless the subflow sets preserve_step_tags").optional(), "type": z.literal("flow") }).describe("Reference to an existing flow by path. Use this to call another flow as a subflow"), z.object({ "modules": z.array(z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.lazy(() => flowModuleValueSchema), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional(), "preview_only": z.boolean().describe("If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run.").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("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").optional(), "show_on_home": z.boolean().describe("If true, a run waiting on this step is listed on the Home page of each user who can approve it. Leave unset when the approval request is sent through another channel (Slack, Discord, email), so it does not sit there unanswered").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("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).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch")).describe("Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'"), "iterator": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs"), "skip_failures": z.boolean().describe("If true, iteration failures don't stop the loop. Failed iterations return null"), "failure_threshold": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "type": z.literal("forloopflow"), "parallel": z.boolean().describe("If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency").optional(), "parallelism": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "squash": z.boolean().optional(), "iteration_label": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional() }).describe("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"), z.object({ "modules": z.array(z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.lazy(() => flowModuleValueSchema), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional(), "preview_only": z.boolean().describe("If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run.").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("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").optional(), "show_on_home": z.boolean().describe("If true, a run waiting on this step is listed on the Home page of each user who can approve it. Leave unset when the approval request is sent through another channel (Slack, Discord, email), so it does not sit there unanswered").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("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).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch")).describe("Steps to execute in each iteration"), "skip_failures": z.boolean().describe("If true, iteration failures don't stop the loop. Failed iterations return null"), "type": z.literal("whileloopflow"), "parallel": z.boolean().describe("If true, iterations run concurrently (use with caution in while loops)").optional(), "parallelism": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "squash": z.boolean().optional(), "max_iterations": z.number().int().gte(1).describe("Maximum number of iterations. Checked after each iteration; when reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'").optional(), "max_duration_secs": z.number().int().gte(1).describe("Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'").optional(), "failure_threshold": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional() }).describe("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.<its_own_id>' 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"), z.object({ "branches": z.array(z.object({ "summary": z.string().describe("Short description of this branch condition").optional(), "expr": z.string().describe("JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins"), "modules": z.array(z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.lazy(() => flowModuleValueSchema), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional(), "preview_only": z.boolean().describe("If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run.").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("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").optional(), "show_on_home": z.boolean().describe("If true, a run waiting on this step is listed on the Home page of each user who can approve it. Leave unset when the approval request is sent through another channel (Slack, Discord, email), so it does not sit there unanswered").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("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).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch")).describe("Steps to execute if this branch's expr is true") })).describe("Array of branches to evaluate in order. The first branch with expr evaluating to true executes"), "default": z.array(z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.lazy(() => flowModuleValueSchema), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional(), "preview_only": z.boolean().describe("If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run.").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("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").optional(), "show_on_home": z.boolean().describe("If true, a run waiting on this step is listed on the Home page of each user who can approve it. Leave unset when the approval request is sent through another channel (Slack, Discord, email), so it does not sit there unanswered").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("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).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch")).describe("Steps to execute if no branch expressions match"), "type": z.literal("branchone") }).describe("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"), z.object({ "branches": z.array(z.object({ "summary": z.string().describe("Short description of this branch's purpose").optional(), "skip_failure": z.boolean().describe("If true, failure in this branch doesn't fail the entire flow").optional(), "modules": z.array(z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.lazy(() => flowModuleValueSchema), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional(), "preview_only": z.boolean().describe("If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run.").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("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").optional(), "show_on_home": z.boolean().describe("If true, a run waiting on this step is listed on the Home page of each user who can approve it. Leave unset when the approval request is sent through another channel (Slack, Discord, email), so it does not sit there unanswered").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("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).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch")).describe("Steps to execute in this branch") })).describe("Array of branches that all execute (either in parallel or sequentially)"), "type": z.literal("branchall"), "parallel": z.boolean().describe("If true, all branches execute concurrently. If false, they execute sequentially").optional(), "parallelism": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional() }).describe("Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently"), z.object({ "type": z.literal("identity"), "flow": z.boolean().describe("If true, marks this as a flow identity (special handling)").optional() }).describe("Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder"), z.object({ "input_transforms": z.object({ "provider": z.discriminatedUnion("type", [z.object({ "value": z.object({ "kind": z.enum(["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]).describe("Supported AI provider types"), "resource": z.string().describe("Resource reference in format '$res:{resource_path}' pointing to provider credentials"), "model": z.string().describe("Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"), "reasoning_effort": z.string().describe("Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default.").optional() }).describe("Complete AI provider configuration with resource reference and model selection"), "type": z.literal("static") }).describe("Static provider configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined").optional(), "output_type": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Output format type.\nValid values: 'text' (default) - plain text response, 'image' - image generation\n").optional(), "user_message": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "system_prompt": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("System instructions that guide the AI's behavior, persona, and response style. Optional.").optional(), "streaming": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "memory": z.discriminatedUnion("type", [z.object({ "value": z.discriminatedUnion("kind", [z.object({ "kind": z.literal("off") }).describe("No conversation memory/context"), z.object({ "kind": z.literal("window"), "context_length": z.number().int().describe("Number of most recent messages to load and store. 0 turns memory off.") }).describe("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"), z.object({ "kind": z.literal("compaction"), "context_window": z.number().int().describe("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").optional() }).describe("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"), z.object({ "kind": z.literal("auto"), "context_length": z.number().int().describe("Maximum number of messages to retain in context").optional(), "memory_id": z.string().describe("Identifier for persistent memory across agent invocations").optional() }).describe("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"), z.object({ "kind": z.literal("manual"), "messages": z.array(z.object({ "role": z.enum(["user","assistant","system"]), "content": z.string() }).describe("A single message in conversation history")) }).describe("Deprecated, still read as it was written. Move the step to `off` with `previous_messages` instead.")]).describe("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`."), "type": z.literal("static") }).describe("Static memory configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined").optional(), "memory_id": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "previous_messages": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "output_schema": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "user_attachments": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "enabled_tools": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "max_completion_tokens": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "temperature": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "max_iterations": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Number. Limits how many times the agent can loop through reasoning and tool use.\nRange: 1-1000.\n").optional(), "model": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "reasoning_effort": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional() }).describe("Input parameters for the AI agent mapped to their values"), "tools": z.array(z.object({ "id": z.string().describe("Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')"), "summary": z.string().describe("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'.").optional(), "description": z.string().describe("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.").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("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.").optional(), "requires_approval": z.boolean().describe("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.").optional(), "background": z.boolean().describe("Flowmodule tools only. The agent is answered as soon as the tool's job starts and keeps working; the job's result reaches it in a later message. If the agent finishes its answer first, it stops without holding a worker until the job is done, then continues with the result.").optional(), "background_after_secs": z.number().int().gte(1).describe("Flowmodule tools only, with background unset. The agent waits up to this many seconds for the tool's job and gets its result as usual; a job still running then continues as a background one, its result reaching the agent in a later message.").optional(), "value": z.any().superRefine((x, ctx) => { const schemas = [z.intersection(z.object({ "tool_type": z.literal("flowmodule") }), z.lazy(() => flowModuleValueSchema)).describe("A tool implemented as a flow module (script, flow, etc.). The AI can call this like any other flow module"), z.object({ "tool_type": z.literal("mcp"), "resource_path": z.string().describe("Path to the MCP resource/server configuration"), "include_tools": z.array(z.string()).describe("Whitelist of specific tools to include from this MCP server").optional(), "exclude_tools": z.array(z.string()).describe("Blacklist of tools to exclude from this MCP server").optional() }).describe("Reference to an external MCP (Model Context Protocol) tool. The AI can call tools from MCP servers"), z.object({ "tool_type": z.literal("websearch") }).describe("A tool implemented as a websearch tool. The AI can call this like any other websearch tool"), z.object({ "tool_type": z.literal("question"), "timeout": z.number().int().describe("Seconds to wait for an answer before the question is reported to the AI as timed out. Defaults to 1800.").optional() }).describe("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.")]; const errors = schemas.reduce<z.ZodError[]>( (errors, schema) => @@ -20,7 +20,7 @@ export const flowModuleValueSchema = z.discriminatedUnion("type", [z.object({ "i }).describe("The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference") }).describe("A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool")).describe("Array of tools the agent can use. The agent decides which tools to call based on the task").optional(), "type": z.literal("aiagent"), "tag": z.string().describe("Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default `flow`)").optional(), "omit_output_from_conversation": z.boolean().describe("If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled.").default(false), "agent": z.string().describe("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").optional(), "tool_inputs": z.record(z.string(), z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs"))).describe("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 — including when\n`agent` is unset, since a step forked for editing keeps these overrides until it is saved\nback or unlinked.\n").optional(), "parallel": z.boolean().describe("If true, the agent can execute multiple tool calls in parallel").optional() }).describe("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"), z.object({ "input_transforms": z.object({ "provider": z.discriminatedUnion("type", [z.object({ "value": z.object({ "kind": z.enum(["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]).describe("Supported AI provider types"), "resource": z.string().describe("Resource reference in format '$res:{resource_path}' pointing to provider credentials"), "model": z.string().describe("Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"), "reasoning_effort": z.string().describe("Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default.").optional() }).describe("Complete AI provider configuration with resource reference and model selection"), "type": z.literal("static") }).describe("Static provider configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined"), "state": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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") }).describe("Input parameters for the decision mapped to their values"), "type": z.literal("aidecision"), "tag": z.string().describe("Worker group tag for execution routing. If not set, the step runs on the flow's tag (default `flow`)").optional() }).describe("AI decision step: one call to a decision model (TypeSafe's Jev, Cloudflare's\nJev-compatible Clef, or OpenAI's or Gemini'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: { <question name>: answer },\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\nthe answers, follow it with a branchone whose branch exprs read\nresults.<id>.output.<question>.choice. Usable as an AI agent tool, where the calling agent\nsupplies the state.\n")]).describe("The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type") -export const flowModuleSchema = z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.discriminatedUnion("type", [z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments"), "content": z.string().describe("The script source code. Should export a 'main' function"), "language": z.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"]).describe("Programming language for this script"), "path": z.string().describe("Optional path for saving this script").optional(), "lock": z.string().describe("Lock file content for dependencies").optional(), "type": z.literal("rawscript"), "tag": z.string().describe("Worker group tag for execution routing").optional(), "concurrent_limit": z.number().describe("Maximum concurrent executions of this script").optional(), "concurrency_time_window_s": z.number().describe("Time window for concurrent_limit").optional(), "on_concurrency_limit": z.enum(["queue","fail"]).describe("What a run of this step does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed.").optional(), "custom_concurrency_key": z.string().describe("Custom key for grouping concurrent executions").optional(), "is_trigger": z.boolean().describe("If true, this script is a trigger that can start the flow").optional(), "assets": z.array(z.object({ "path": z.string().describe("Path to the asset"), "kind": z.enum(["s3object","resource","ducklake","datatable","volume","dbt"]).describe("Type of asset"), "access_type": z.union([z.literal("r"), z.literal("w"), z.literal("rw"), z.literal(null)]).nullable().describe("Access level for this asset").optional(), "alt_access_type": z.union([z.literal("r"), z.literal("w"), z.literal("rw"), z.literal(null)]).nullable().describe("Alternative access level").optional() })).describe("External resources this script accesses (S3 objects, resources, etc.)").optional() }).describe("Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms"), z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments"), "path": z.string().describe("Path to the script in the workspace (e.g., 'f/scripts/send_email')"), "hash": z.string().describe("Optional specific version hash of the script to use").optional(), "type": z.literal("script"), "tag_override": z.string().describe("Override the script's default worker group tag").optional(), "is_trigger": z.boolean().describe("If true, this script is a trigger that can start the flow").optional() }).describe("Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code"), z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments"), "path": z.string().describe("Path to the flow in the workspace (e.g., 'f/flows/process_user')"), "tag_override": z.string().describe("Override the subflow's worker group tag. Its steps run on this tag unless the subflow sets preserve_step_tags").optional(), "type": z.literal("flow") }).describe("Reference to an existing flow by path. Use this to call another flow as a subflow"), z.object({ "modules": z.array(z.lazy(() => flowModuleSchema)).describe("Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'"), "iterator": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs"), "skip_failures": z.boolean().describe("If true, iteration failures don't stop the loop. Failed iterations return null"), "type": z.literal("forloopflow"), "parallel": z.boolean().describe("If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency").optional(), "parallelism": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "squash": z.boolean().optional(), "iteration_label": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional() }).describe("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"), z.object({ "modules": z.array(z.lazy(() => flowModuleSchema)).describe("Steps to execute in each iteration"), "skip_failures": z.boolean().describe("If true, iteration failures don't stop the loop. Failed iterations return null"), "type": z.literal("whileloopflow"), "parallel": z.boolean().describe("If true, iterations run concurrently (use with caution in while loops)").optional(), "parallelism": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "squash": z.boolean().optional(), "max_iterations": z.number().int().gte(1).describe("Maximum number of iterations. Checked after each iteration; when reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'").optional(), "max_duration_secs": z.number().int().gte(1).describe("Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'").optional() }).describe("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.<its_own_id>' 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"), z.object({ "branches": z.array(z.object({ "summary": z.string().describe("Short description of this branch condition").optional(), "expr": z.string().describe("JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins"), "modules": z.array(z.lazy(() => flowModuleSchema)).describe("Steps to execute if this branch's expr is true") })).describe("Array of branches to evaluate in order. The first branch with expr evaluating to true executes"), "default": z.array(z.lazy(() => flowModuleSchema)).describe("Steps to execute if no branch expressions match"), "type": z.literal("branchone") }).describe("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"), z.object({ "branches": z.array(z.object({ "summary": z.string().describe("Short description of this branch's purpose").optional(), "skip_failure": z.boolean().describe("If true, failure in this branch doesn't fail the entire flow").optional(), "modules": z.array(z.lazy(() => flowModuleSchema)).describe("Steps to execute in this branch") })).describe("Array of branches that all execute (either in parallel or sequentially)"), "type": z.literal("branchall"), "parallel": z.boolean().describe("If true, all branches execute concurrently. If false, they execute sequentially").optional(), "parallelism": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional() }).describe("Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently"), z.object({ "type": z.literal("identity"), "flow": z.boolean().describe("If true, marks this as a flow identity (special handling)").optional() }).describe("Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder"), z.object({ "input_transforms": z.object({ "provider": z.discriminatedUnion("type", [z.object({ "value": z.object({ "kind": z.enum(["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]).describe("Supported AI provider types"), "resource": z.string().describe("Resource reference in format '$res:{resource_path}' pointing to provider credentials"), "model": z.string().describe("Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"), "reasoning_effort": z.string().describe("Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default.").optional() }).describe("Complete AI provider configuration with resource reference and model selection"), "type": z.literal("static") }).describe("Static provider configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined").optional(), "output_type": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Output format type.\nValid values: 'text' (default) - plain text response, 'image' - image generation\n").optional(), "user_message": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "system_prompt": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("System instructions that guide the AI's behavior, persona, and response style. Optional.").optional(), "streaming": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "memory": z.discriminatedUnion("type", [z.object({ "value": z.discriminatedUnion("kind", [z.object({ "kind": z.literal("off") }).describe("No conversation memory/context"), z.object({ "kind": z.literal("window"), "context_length": z.number().int().describe("Number of most recent messages to load and store. 0 turns memory off.") }).describe("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"), z.object({ "kind": z.literal("compaction"), "context_window": z.number().int().describe("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").optional() }).describe("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"), z.object({ "kind": z.literal("auto"), "context_length": z.number().int().describe("Maximum number of messages to retain in context").optional(), "memory_id": z.string().describe("Identifier for persistent memory across agent invocations").optional() }).describe("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"), z.object({ "kind": z.literal("manual"), "messages": z.array(z.object({ "role": z.enum(["user","assistant","system"]), "content": z.string() }).describe("A single message in conversation history")) }).describe("Deprecated, still read as it was written. Move the step to `off` with `previous_messages` instead.")]).describe("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`."), "type": z.literal("static") }).describe("Static memory configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined").optional(), "memory_id": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "previous_messages": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "output_schema": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "user_attachments": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "enabled_tools": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "max_completion_tokens": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "temperature": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "max_iterations": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Number. Limits how many times the agent can loop through reasoning and tool use.\nRange: 1-1000.\n").optional(), "model": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "reasoning_effort": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional() }).describe("Input parameters for the AI agent mapped to their values"), "tools": z.array(z.object({ "id": z.string().describe("Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')"), "summary": z.string().describe("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'.").optional(), "description": z.string().describe("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.").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("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.").optional(), "requires_approval": z.boolean().describe("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.").optional(), "background": z.boolean().describe("Flowmodule tools only. The agent is answered as soon as the tool's job starts and keeps working; the job's result reaches it in a later message. If the agent finishes its answer first, it stops without holding a worker until the job is done, then continues with the result.").optional(), "background_after_secs": z.number().int().gte(1).describe("Flowmodule tools only, with background unset. The agent waits up to this many seconds for the tool's job and gets its result as usual; a job still running then continues as a background one, its result reaching the agent in a later message.").optional(), "value": z.any().superRefine((x, ctx) => { +export const flowModuleSchema = z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.discriminatedUnion("type", [z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments"), "content": z.string().describe("The script source code. Should export a 'main' function"), "language": z.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"]).describe("Programming language for this script"), "path": z.string().describe("Optional path for saving this script").optional(), "lock": z.string().describe("Lock file content for dependencies").optional(), "type": z.literal("rawscript"), "tag": z.string().describe("Worker group tag for execution routing").optional(), "concurrent_limit": z.number().describe("Maximum concurrent executions of this script").optional(), "concurrency_time_window_s": z.number().describe("Time window for concurrent_limit").optional(), "on_concurrency_limit": z.enum(["queue","fail"]).describe("What a run of this step does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed.").optional(), "custom_concurrency_key": z.string().describe("Custom key for grouping concurrent executions").optional(), "is_trigger": z.boolean().describe("If true, this script is a trigger that can start the flow").optional(), "assets": z.array(z.object({ "path": z.string().describe("Path to the asset"), "kind": z.enum(["s3object","resource","ducklake","datatable","volume","dbt"]).describe("Type of asset"), "access_type": z.union([z.literal("r"), z.literal("w"), z.literal("rw"), z.literal(null)]).nullable().describe("Access level for this asset").optional(), "alt_access_type": z.union([z.literal("r"), z.literal("w"), z.literal("rw"), z.literal(null)]).nullable().describe("Alternative access level").optional() })).describe("External resources this script accesses (S3 objects, resources, etc.)").optional() }).describe("Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms"), z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments"), "path": z.string().describe("Path to the script in the workspace (e.g., 'f/scripts/send_email')"), "hash": z.string().describe("Optional specific version hash of the script to use").optional(), "type": z.literal("script"), "tag_override": z.string().describe("Override the script's default worker group tag").optional(), "is_trigger": z.boolean().describe("If true, this script is a trigger that can start the flow").optional() }).describe("Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code"), z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments"), "path": z.string().describe("Path to the flow in the workspace (e.g., 'f/flows/process_user')"), "tag_override": z.string().describe("Override the subflow's worker group tag. Its steps run on this tag unless the subflow sets preserve_step_tags").optional(), "type": z.literal("flow") }).describe("Reference to an existing flow by path. Use this to call another flow as a subflow"), z.object({ "modules": z.array(z.lazy(() => flowModuleSchema)).describe("Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'"), "iterator": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs"), "skip_failures": z.boolean().describe("If true, iteration failures don't stop the loop. Failed iterations return null"), "failure_threshold": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "type": z.literal("forloopflow"), "parallel": z.boolean().describe("If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency").optional(), "parallelism": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "squash": z.boolean().optional(), "iteration_label": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional() }).describe("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"), z.object({ "modules": z.array(z.lazy(() => flowModuleSchema)).describe("Steps to execute in each iteration"), "skip_failures": z.boolean().describe("If true, iteration failures don't stop the loop. Failed iterations return null"), "type": z.literal("whileloopflow"), "parallel": z.boolean().describe("If true, iterations run concurrently (use with caution in while loops)").optional(), "parallelism": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "squash": z.boolean().optional(), "max_iterations": z.number().int().gte(1).describe("Maximum number of iterations. Checked after each iteration; when reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'").optional(), "max_duration_secs": z.number().int().gte(1).describe("Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'").optional(), "failure_threshold": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional() }).describe("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.<its_own_id>' 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"), z.object({ "branches": z.array(z.object({ "summary": z.string().describe("Short description of this branch condition").optional(), "expr": z.string().describe("JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins"), "modules": z.array(z.lazy(() => flowModuleSchema)).describe("Steps to execute if this branch's expr is true") })).describe("Array of branches to evaluate in order. The first branch with expr evaluating to true executes"), "default": z.array(z.lazy(() => flowModuleSchema)).describe("Steps to execute if no branch expressions match"), "type": z.literal("branchone") }).describe("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"), z.object({ "branches": z.array(z.object({ "summary": z.string().describe("Short description of this branch's purpose").optional(), "skip_failure": z.boolean().describe("If true, failure in this branch doesn't fail the entire flow").optional(), "modules": z.array(z.lazy(() => flowModuleSchema)).describe("Steps to execute in this branch") })).describe("Array of branches that all execute (either in parallel or sequentially)"), "type": z.literal("branchall"), "parallel": z.boolean().describe("If true, all branches execute concurrently. If false, they execute sequentially").optional(), "parallelism": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional() }).describe("Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently"), z.object({ "type": z.literal("identity"), "flow": z.boolean().describe("If true, marks this as a flow identity (special handling)").optional() }).describe("Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder"), z.object({ "input_transforms": z.object({ "provider": z.discriminatedUnion("type", [z.object({ "value": z.object({ "kind": z.enum(["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]).describe("Supported AI provider types"), "resource": z.string().describe("Resource reference in format '$res:{resource_path}' pointing to provider credentials"), "model": z.string().describe("Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"), "reasoning_effort": z.string().describe("Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default.").optional() }).describe("Complete AI provider configuration with resource reference and model selection"), "type": z.literal("static") }).describe("Static provider configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined").optional(), "output_type": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Output format type.\nValid values: 'text' (default) - plain text response, 'image' - image generation\n").optional(), "user_message": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "system_prompt": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("System instructions that guide the AI's behavior, persona, and response style. Optional.").optional(), "streaming": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "memory": z.discriminatedUnion("type", [z.object({ "value": z.discriminatedUnion("kind", [z.object({ "kind": z.literal("off") }).describe("No conversation memory/context"), z.object({ "kind": z.literal("window"), "context_length": z.number().int().describe("Number of most recent messages to load and store. 0 turns memory off.") }).describe("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"), z.object({ "kind": z.literal("compaction"), "context_window": z.number().int().describe("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").optional() }).describe("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"), z.object({ "kind": z.literal("auto"), "context_length": z.number().int().describe("Maximum number of messages to retain in context").optional(), "memory_id": z.string().describe("Identifier for persistent memory across agent invocations").optional() }).describe("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"), z.object({ "kind": z.literal("manual"), "messages": z.array(z.object({ "role": z.enum(["user","assistant","system"]), "content": z.string() }).describe("A single message in conversation history")) }).describe("Deprecated, still read as it was written. Move the step to `off` with `previous_messages` instead.")]).describe("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`."), "type": z.literal("static") }).describe("Static memory configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined").optional(), "memory_id": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "previous_messages": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "output_schema": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "user_attachments": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "enabled_tools": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "max_completion_tokens": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "temperature": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "max_iterations": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Number. Limits how many times the agent can loop through reasoning and tool use.\nRange: 1-1000.\n").optional(), "model": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional(), "reasoning_effort": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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").optional() }).describe("Input parameters for the AI agent mapped to their values"), "tools": z.array(z.object({ "id": z.string().describe("Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')"), "summary": z.string().describe("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'.").optional(), "description": z.string().describe("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.").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("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.").optional(), "requires_approval": z.boolean().describe("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.").optional(), "background": z.boolean().describe("Flowmodule tools only. The agent is answered as soon as the tool's job starts and keeps working; the job's result reaches it in a later message. If the agent finishes its answer first, it stops without holding a worker until the job is done, then continues with the result.").optional(), "background_after_secs": z.number().int().gte(1).describe("Flowmodule tools only, with background unset. The agent waits up to this many seconds for the tool's job and gets its result as usual; a job still running then continues as a background one, its result reaching the agent in a later message.").optional(), "value": z.any().superRefine((x, ctx) => { const schemas = [z.intersection(z.object({ "tool_type": z.literal("flowmodule") }), z.lazy(() => flowModuleValueSchema)).describe("A tool implemented as a flow module (script, flow, etc.). The AI can call this like any other flow module"), z.object({ "tool_type": z.literal("mcp"), "resource_path": z.string().describe("Path to the MCP resource/server configuration"), "include_tools": z.array(z.string()).describe("Whitelist of specific tools to include from this MCP server").optional(), "exclude_tools": z.array(z.string()).describe("Blacklist of tools to exclude from this MCP server").optional() }).describe("Reference to an external MCP (Model Context Protocol) tool. The AI can call tools from MCP servers"), z.object({ "tool_type": z.literal("websearch") }).describe("A tool implemented as a websearch tool. The AI can call this like any other websearch tool"), z.object({ "tool_type": z.literal("question"), "timeout": z.number().int().describe("Seconds to wait for an answer before the question is reported to the AI as timed out. Defaults to 1800.").optional() }).describe("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.")]; const errors = schemas.reduce<z.ZodError[]>( (errors, schema) => @@ -37,7 +37,7 @@ export const flowModuleSchema = z.object({ "id": z.string().describe("Unique ide message: "Invalid input: Should pass single schema", }); } - }).describe("The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference") }).describe("A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool")).describe("Array of tools the agent can use. The agent decides which tools to call based on the task").optional(), "type": z.literal("aiagent"), "tag": z.string().describe("Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default `flow`)").optional(), "omit_output_from_conversation": z.boolean().describe("If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled.").default(false), "agent": z.string().describe("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").optional(), "tool_inputs": z.record(z.string(), z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs"))).describe("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 — including when\n`agent` is unset, since a step forked for editing keeps these overrides until it is saved\nback or unlinked.\n").optional(), "parallel": z.boolean().describe("If true, the agent can execute multiple tool calls in parallel").optional() }).describe("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"), z.object({ "input_transforms": z.object({ "provider": z.discriminatedUnion("type", [z.object({ "value": z.object({ "kind": z.enum(["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]).describe("Supported AI provider types"), "resource": z.string().describe("Resource reference in format '$res:{resource_path}' pointing to provider credentials"), "model": z.string().describe("Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"), "reasoning_effort": z.string().describe("Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default.").optional() }).describe("Complete AI provider configuration with resource reference and model selection"), "type": z.literal("static") }).describe("Static provider configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined"), "state": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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") }).describe("Input parameters for the decision mapped to their values"), "type": z.literal("aidecision"), "tag": z.string().describe("Worker group tag for execution routing. If not set, the step runs on the flow's tag (default `flow`)").optional() }).describe("AI decision step: one call to a decision model (TypeSafe's Jev, Cloudflare's\nJev-compatible Clef, or OpenAI's or Gemini'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: { <question name>: answer },\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\nthe answers, follow it with a branchone whose branch exprs read\nresults.<id>.output.<question>.choice. Usable as an AI agent tool, where the calling agent\nsupplies the state.\n")]).describe("The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type"), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional(), "preview_only": z.boolean().describe("If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run.").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("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").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("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).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch") + }).describe("The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference") }).describe("A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool")).describe("Array of tools the agent can use. The agent decides which tools to call based on the task").optional(), "type": z.literal("aiagent"), "tag": z.string().describe("Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default `flow`)").optional(), "omit_output_from_conversation": z.boolean().describe("If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled.").default(false), "agent": z.string().describe("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").optional(), "tool_inputs": z.record(z.string(), z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs"))).describe("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 — including when\n`agent` is unset, since a step forked for editing keeps these overrides until it is saved\nback or unlinked.\n").optional(), "parallel": z.boolean().describe("If true, the agent can execute multiple tool calls in parallel").optional() }).describe("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"), z.object({ "input_transforms": z.object({ "provider": z.discriminatedUnion("type", [z.object({ "value": z.object({ "kind": z.enum(["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]).describe("Supported AI provider types"), "resource": z.string().describe("Resource reference in format '$res:{resource_path}' pointing to provider credentials"), "model": z.string().describe("Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"), "reasoning_effort": z.string().describe("Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default.").optional() }).describe("Complete AI provider configuration with resource reference and model selection"), "type": z.literal("static") }).describe("Static provider configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined"), "state": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("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") }).describe("Input parameters for the decision mapped to their values"), "type": z.literal("aidecision"), "tag": z.string().describe("Worker group tag for execution routing. If not set, the step runs on the flow's tag (default `flow`)").optional() }).describe("AI decision step: one call to a decision model (TypeSafe's Jev, Cloudflare's\nJev-compatible Clef, or OpenAI's or Gemini'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: { <question name>: answer },\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\nthe answers, follow it with a branchone whose branch exprs read\nresults.<id>.output.<question>.choice. Usable as an AI agent tool, where the calling agent\nsupplies the state.\n")]).describe("The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type"), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("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.").optional(), "error_include_result": z.boolean().describe("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.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional(), "preview_only": z.boolean().describe("If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run.").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("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')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("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").optional(), "show_on_home": z.boolean().describe("If true, a run waiting on this step is listed on the Home page of each user who can approve it. Leave unset when the approval request is sent through another channel (Slack, Discord, email), so it does not sit there unanswered").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("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).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch") export const flowModulesSchema = z.array(flowModuleSchema) diff --git a/frontend/src/lib/components/copilot/chat/global/core.test.ts b/frontend/src/lib/components/copilot/chat/global/core.test.ts index 1b2e30104a..c7d3fbe9ad 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.test.ts @@ -1,3 +1,4 @@ +import { createCodeSelection } from '../context' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' vi.mock('monaco-editor', () => ({ @@ -3685,6 +3686,19 @@ describe('session-only preview tools gating', () => { expect(content).toContain('search_dom') }) + it('carries selected code, naming the item it belongs to', () => { + const content = prepareGlobalUserMessage('Simplify', [ + createCodeSelection( + { kind: 'flow', path: 'f/shop/sync', part: 'a' }, + { content: 'const s = `x`\n// ```', startLine: 3, endLine: 4, lang: 'bun' } + ) + ]).content as string + expect(content).toContain('## SELECTED CODE') + expect(content).toContain( + '- type: flow, path: f/shop/sync, step: a, lines 3-4:\n````bun\nconst s = `x`\n// ```\n````' + ) + }) + // The instruction headers are matched by their distinctive parenthetical so the // guidance bullet (which references both block names) doesn't false-positive. const WS_HEADER = 'WORKSPACE INSTRUCTIONS (configured by a workspace admin' diff --git a/frontend/src/lib/components/copilot/chat/global/core.ts b/frontend/src/lib/components/copilot/chat/global/core.ts index 4e747bfc13..2fc69df17a 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -23,6 +23,7 @@ import { deepEqual } from 'fast-equals' import { promptSafe, type ArtifactVersionTarget, + type ImageSource, type S3FileRef } from '$lib/components/sessions/previewRouter' import { canDraftItem, roleCanDraft } from '$lib/editRights' @@ -130,7 +131,14 @@ import { import { secretRequestToolResult } from '../secretRequest' import { scriptLangToEditorLang } from '$lib/scripts' import { appFileEditorLang } from '../appFileEditorLang' -import { isMentionContext, isUserContextPath, type ContextElement } from '../context' +import { + isCodeSelection, + isMentionContext, + isUserContextPath, + type CodeSelection, + type CodeSource, + type ContextElement +} from '../context' import { getDatatableTools } from '../datatableTools' import { getDatatableMigrationTools } from '../datatableMigrationTools' import { getDucklakeTools } from '../ducklakeTools' @@ -4879,7 +4887,8 @@ export const SESSION_PREVIEW_TOOL_NAMES = new Set([ 'update_artifact', 'list_artifacts', 'read_artifact', - 'list_artifact_versions' + 'list_artifact_versions', + 'show_image' ]) /** @@ -4953,6 +4962,7 @@ export type GlobalToolHelpers = SessionToolHelpers & { getChatId?: () => string | undefined openArtifact?: (artifactId: string, name: string, version?: ArtifactVersionTarget) => void openS3File?: (file: S3FileRef) => void + openImage?: (source: ImageSource, label: string) => void } function sessionIdFromCtx(ctx: { helpers?: unknown }): string | undefined { @@ -7885,6 +7895,22 @@ export function getActiveGlobalEditorContext( } } +const CODE_PART_LABEL: Record<CodeSource['kind'], string> = { + script: 'module file', + flow: 'step', + raw_app: 'backend runnable', + agent: 'tool' +} + +function codeSelectionBlock(selection: CodeSelection): string { + const { kind, path, part } = selection.source + const where = part ? `, ${CODE_PART_LABEL[kind]}: ${part}` : '' + // Longer than any run in the code, so the code cannot close its own fence. + const runs = selection.content.match(/`+/g) ?? [] + const fence = '`'.repeat(Math.max(3, ...runs.map((r) => r.length + 1))) + return `- type: ${kind}, path: ${path}${where}, lines ${selection.startLine}-${selection.endLine}:\n${fence}${selection.lang}\n${selection.content}\n${fence}\n` +} + export function prepareGlobalUserMessage( instructions: string, selectedContext: ContextElement[] = [], @@ -7955,6 +7981,15 @@ export function prepareGlobalUserMessage( content += '\n' } + const codeSelections = selectedContext.filter(isCodeSelection) + if (codeSelections.length > 0) { + content += '## SELECTED CODE\n' + content += + 'The user selected this code in an editor, and the instructions are about it. To change it, edit the item named above it. The code is as it was when selected, so the item may have changed since.\n' + content += codeSelections.map(codeSelectionBlock).join('') + content += '\n' + } + const files = options.files ?? [] if (files.length > 0) { content += '## ATTACHED FILES\n' diff --git a/frontend/src/lib/components/copilot/chat/global/mcpTools.test.ts b/frontend/src/lib/components/copilot/chat/global/mcpTools.test.ts index 8a95f6032a..eb07d22b62 100644 --- a/frontend/src/lib/components/copilot/chat/global/mcpTools.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/mcpTools.test.ts @@ -36,6 +36,7 @@ import { splitMcpResult, type McpServer } from './mcpTools' +import { mcpUnavailableMessage } from './mcpUnavailable' import { setMcpEnabled } from '$lib/components/mcp/enabledServers' const SERVERS: McpServer[] = [{ path: 'u/hugo/github_mcp' }] @@ -491,6 +492,25 @@ describe('loadMcpServers', () => { expect(await loadMcpServers('test-ws')).toEqual([{ path: 'u/hugo/github_mcp' }]) }) + it('tells a turned-off server apart from one that is not connected', async () => { + expect(await mcpUnavailableMessage('test-ws', 'f/team/shared_mcp')).toContain( + '"f/team/shared_mcp" is connected but turned off' + ) + expect(await mcpUnavailableMessage('test-ws', 'f/team/gone_mcp')).toContain( + 'No MCP server "f/team/gone_mcp" is connected' + ) + }) + + it('reports a plain-text error body when listing fails', async () => { + listResourceMock.mockRejectedValueOnce({ + body: 'database is down', + message: 'Internal Server Error' + }) + expect(await mcpUnavailableMessage('test-ws', 'f/team/shared_mcp')).toBe( + 'Could not list the MCP servers: database is down' + ) + }) + it('does not carry an enabled server into another workspace', async () => { setMcpEnabled('test-ws', 'u/hugo/github_mcp', true) expect(await loadMcpServers('other-ws')).toEqual([]) diff --git a/frontend/src/lib/components/copilot/chat/global/mcpTools.ts b/frontend/src/lib/components/copilot/chat/global/mcpTools.ts index e81a5db49c..ebd0d3460c 100644 --- a/frontend/src/lib/components/copilot/chat/global/mcpTools.ts +++ b/frontend/src/lib/components/copilot/chat/global/mcpTools.ts @@ -3,7 +3,8 @@ import { ResourceService, type GetMcpToolsResponse } from '$lib/gen' import { createToolDef } from '../shared' import { NONE, type SessionTool } from '../sessionCapabilities' import { enabledMcpPaths } from '$lib/components/mcp/enabledServers' -import { isOwnOrSharedMcpPath, MCP_LIST_PER_PAGE, mcpViewer } from '$lib/components/mcp/ownServers' +import { listVisibleMcpServers } from '$lib/components/mcp/ownServers' +import { mcpUnavailableMessage } from './mcpUnavailable' import { MAX_ATTACHED_IMAGES, type AttachedImage } from '../imageUtils' import { chatModelSeesImages, toolImagesFor } from './toolImages' @@ -98,19 +99,7 @@ export async function loadMcpServers(workspace: string): Promise<McpServer[]> { const enabled = enabledMcpPaths(workspace) if (enabled.length === 0) return [] try { - const [resources, viewer] = await Promise.all([ - ResourceService.listResource({ - workspace, - resourceType: 'mcp', - perPage: MCP_LIST_PER_PAGE - }), - mcpViewer(workspace) - ]) - return resources - .filter( - (r) => enabled.includes(r.path) && isOwnOrSharedMcpPath(r.path, r.extra_perms, viewer) - ) - .map((r) => ({ path: r.path, editedAt: r.edited_at })) + return (await listVisibleMcpServers(workspace)).filter((s) => enabled.includes(s.path)) } catch (e) { console.error('Failed to load MCP servers', e) return [] @@ -176,9 +165,7 @@ async function resolveTool( ): Promise<{ server: McpServer; tool: McpToolDef } | { error: string }> { const server = servers.find((s) => s.path === serverPath) if (!server) { - return { - error: `Unknown MCP server "${serverPath}". Connected servers: ${servers.map((s) => s.path).join(', ')}` - } + return { error: await mcpUnavailableMessage(workspace, serverPath) } } const tools = await loadServerTools(workspace, server.path, server.editedAt) const tool = tools.find((t) => t.name === toolName) diff --git a/frontend/src/lib/components/copilot/chat/global/mcpUnavailable.ts b/frontend/src/lib/components/copilot/chat/global/mcpUnavailable.ts new file mode 100644 index 0000000000..7dd0803daf --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/global/mcpUnavailable.ts @@ -0,0 +1,43 @@ +import { enabledMcpPaths } from '$lib/components/mcp/enabledServers' +import { listVisibleMcpServers } from '$lib/components/mcp/ownServers' + +const TURN_ON = + 'The user turns servers on in the chat settings, under MCP connections; the setting is kept per browser.' + +/** + * Why an MCP call cannot reach `path` (or any server, when the MCP tools are not + * registered at all). Listed only on this error path, so a workspace without MCP + * still pays nothing per iteration. Names only servers the user can see in MCP + * connections, so it reveals nothing the settings page would not. + */ +export async function mcpUnavailableMessage(workspace: string, path?: string): Promise<string> { + let visible: string[] + try { + visible = (await listVisibleMcpServers(workspace)).map((s) => s.path) + } catch (e: any) { + return `Could not list the MCP servers: ${e?.body?.error?.message ?? e?.body ?? e?.message ?? String(e)}` + } + const enabled = new Set(enabledMcpPaths(workspace)) + const on = visible.filter((p) => enabled.has(p)) + const off = visible.filter((p) => !enabled.has(p)) + + if (path && off.includes(path)) { + return `MCP server "${path}" is connected but turned off. ${TURN_ON}` + } + // A server that is on yet has no tools registered means the chat is not in global mode. + if (path ? on.includes(path) : on.length > 0) { + return 'MCP tools are only available in global mode. Use change_mode to switch.' + } + if (visible.length === 0) { + return 'No MCP server is connected in this workspace. The user connects one in the chat settings, under MCP connections.' + } + return [ + path + ? `No MCP server "${path}" is connected in this workspace.` + : 'No MCP server is turned on.', + on.length > 0 ? `Turned on: ${on.join(', ')}.` : '', + off.length > 0 ? `Connected but turned off: ${off.join(', ')}. ${TURN_ON}` : '' + ] + .filter(Boolean) + .join(' ') +} diff --git a/frontend/src/lib/components/copilot/chat/global/rawAppBundlerBridge.ts b/frontend/src/lib/components/copilot/chat/global/rawAppBundlerBridge.ts index 62dce8af5c..00a87e7657 100644 --- a/frontend/src/lib/components/copilot/chat/global/rawAppBundlerBridge.ts +++ b/frontend/src/lib/components/copilot/chat/global/rawAppBundlerBridge.ts @@ -1,5 +1,6 @@ import { WorkspaceService } from '$lib/gen' import { randomUUID } from '$lib/utils/uuid' +import { uiBuilderFiles } from '$lib/components/raw_apps/utils' export type RawAppBundle = { js: string @@ -91,7 +92,7 @@ export function bundleRawAppFiles({ postToBundler({ type: 'bundleRawApp', requestId, - files, + files: uiBuilderFiles(files), sharedUiFiles, bundlerType }) diff --git a/frontend/src/lib/components/copilot/chat/messageS3Object.test.ts b/frontend/src/lib/components/copilot/chat/messageS3Object.test.ts new file mode 100644 index 0000000000..6d7f9306d0 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/messageS3Object.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'vitest' +import { messageS3Object } from './messageS3Object' + +describe('messageS3Object', () => { + it('reads the file of an s3 object answer', () => { + expect(messageS3Object('{"type":"windmill_s3_object","s3":"out/report.pdf"}')).toEqual({ + s3: 'out/report.pdf' + }) + expect( + messageS3Object('{"type":"windmill_s3_object","s3":"a.png","storage":"secondary"}') + ).toEqual({ s3: 'a.png', storage: 'secondary' }) + }) + + it('keeps only the file fields, whatever else the answer carries', () => { + const content = JSON.stringify({ + type: 'windmill_s3_object', + s3: 'a.png', + resume: '/x', + cancel: '/y', + approvalPage: 'https://example.com', + wm_renderer: 'html', + html: '<b>hi</b>', + presigned: 'a=b' + }) + expect(messageS3Object(content)).toEqual({ s3: 'a.png' }) + }) + + it('leaves any other answer to the text renderer', () => { + expect(messageS3Object('hello')).toBeUndefined() + expect(messageS3Object('{not json')).toBeUndefined() + expect(messageS3Object('{"type":"other","s3":"a.png"}')).toBeUndefined() + expect(messageS3Object('{"type":"windmill_s3_object","s3":{"k":1}}')).toBeUndefined() + expect(messageS3Object('{"type":"windmill_s3_object","s3":""}')).toBeUndefined() + expect(messageS3Object('{"type":"windmill_s3_object","s3":"a.png","storage":3}')).toEqual({ + s3: 'a.png' + }) + }) +}) diff --git a/frontend/src/lib/components/copilot/chat/messageS3Object.ts b/frontend/src/lib/components/copilot/chat/messageS3Object.ts new file mode 100644 index 0000000000..14e3dba431 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/messageS3Object.ts @@ -0,0 +1,20 @@ +/** + * The file a flow step's answer names, when the answer is an S3 object rather than text. + * + * Only `s3` and `storage` are kept: the result viewer picks its renderer from the keys it is + * handed (`approvalPage`, `wm_renderer`, an agent trace, ...), and a stored message must not + * choose how it is displayed. + */ +export function messageS3Object(content: string): { s3: string; storage?: string } | undefined { + if (!content.startsWith('{')) return undefined + let parsed: unknown + try { + parsed = JSON.parse(content) + } catch { + return undefined + } + if (!parsed || typeof parsed !== 'object') return undefined + const { type, s3, storage } = parsed as Record<string, unknown> + if (type !== 'windmill_s3_object' || typeof s3 !== 'string' || !s3) return undefined + return typeof storage === 'string' && storage ? { s3, storage } : { s3 } +} diff --git a/frontend/src/lib/components/copilot/chat/script/core.ts b/frontend/src/lib/components/copilot/chat/script/core.ts index 13e78f985f..063708887d 100644 --- a/frontend/src/lib/components/copilot/chat/script/core.ts +++ b/frontend/src/lib/components/copilot/chat/script/core.ts @@ -268,102 +268,6 @@ function buildChatSystemPrompt(currentModel: AIProviderModel) { ` } -export const INLINE_CHAT_SYSTEM_PROMPT = ` -# Windmill Inline Coding Assistant - -You are a coding assistant for the Windmill platform. You provide precise code modifications based on user instructions. - -## Input Format - -You will receive: -- **INSTRUCTIONS**: User's modification request -- **CODE**: Current code content with modification boundaries -- **DATABASES** *(optional)*: Available workspace databases - -### Code Boundaries - -The code contains \`[#START]\` and \`[#END]\` markers indicating the modification scope: -- **MUST** only modify code between these markers -- **MUST** remove the markers in your response -- **MUST** preserve all other code exactly as provided - -## Task Requirements - -Return the modified CODE that fulfills the user's request. Assume all user queries are valid and actionable. - -### Critical Rules - -- ✅ **ALWAYS** include a single code block with the entire updated CODE -- ✅ **ALWAYS** use the structured XML output format below -- ❌ **NEVER** include only modified sections -- ❌ **NEVER** add explanatory text or comments outside the format -- ❌ **NEVER** include \`\`\` code fences in your response -- ❌ **NEVER** modify the code outside the boundaries - -## Output Format - -\`\`\`xml -<changes_made> -Brief description of what was changed -</changes_made> -<new_code> -[complete modified code without markers] -</new_code> -\`\`\` - -## Example - -### Input: -\`\`\`xml -<user_request> -INSTRUCTIONS: -Return 2 instead of 1 - -CODE: -import * as wmill from "windmill-client" - -function test() { - return "hello" -} - -[#START] -export async function main() { - return 1; -} -[#END] -</user_request> -\`\`\` - -### Expected Output: -\`\`\`xml -<changes_made> -Changed return value from 1 to 2 in main function -</changes_made> -<new_code> -import * as wmill from "windmill-client" - -function test() { - return "hello" -} - -export async function main() { - return 2; -} -</new_code> -\`\`\` -` - -export function prepareInlineChatSystemPrompt( - lang: ScriptLang | 'bunnative', - options: { workflowAsCode?: boolean } = {} -) { - return ( - INLINE_CHAT_SYSTEM_PROMPT + - '\n\n' + - getLangContext(lang, { allowResourcesFetch: true, workflowAsCode: options.workflowAsCode }) - ) -} - export const CHAT_USER_PROMPT = ` INSTRUCTIONS: {instructions} diff --git a/frontend/src/lib/components/copilot/chat/shared.ts b/frontend/src/lib/components/copilot/chat/shared.ts index 4d639eabf2..ce45758950 100644 --- a/frontend/src/lib/components/copilot/chat/shared.ts +++ b/frontend/src/lib/components/copilot/chat/shared.ts @@ -39,11 +39,11 @@ import { get } from 'svelte/store' import type { PasteAttachment } from './pasteTokens' import { dataUrlToImagePart, type AttachedImage } from './imageUtils' import type { AttachedTextFile } from './textFileUtils' -import type { CodePieceElement, ContextElement, FlowModuleCodePieceElement } from './context' +import type { ContextElement } from './context' import { isUserContextPath } from './context' import { workspaceStore } from '$lib/stores' import type { ExtendedOpenFlow } from '$lib/components/flows/types' -import { findModuleInFlow, findModuleInModules } from '$lib/components/flows/flowTree' +import { findModuleInFlow } from '$lib/components/flows/flowTree' import { agentTestInputTransforms } from '$lib/components/flows/agentFormFields' import type { FunctionParameters } from 'openai/resources/shared.mjs' import { z } from 'zod' @@ -80,6 +80,7 @@ import type { editor as meditor } from 'monaco-editor' import { pendingFolderInstructions, type FolderInstructionsContext } from './folderInstructions' import type { WebSearchSource } from './webSearchResult' import { runOnServer } from './global/backendSessionTools' +import { mcpUnavailableMessage } from './global/mcpUnavailable' import { isAgentStream } from '../../aiAgentResult' // Prettify function for code arguments - extracts and formats code from JSON @@ -355,48 +356,6 @@ export const extractAllModules = (modules: FlowModule[]): FlowModule[] => { }) } -const applyCodePieceToCodeContext = (codePieces: CodePieceElement[], codeContext: string) => { - let code = codeContext.split('\n') - let shiftOffset = 0 - codePieces.sort((a, b) => a.startLine - b.startLine) - for (const codePiece of codePieces) { - code.splice(codePiece.endLine + shiftOffset, 0, '[#END]') - code.splice(codePiece.startLine + shiftOffset - 1, 0, '[#START]') - shiftOffset += 2 - } - return code.join('\n') -} - -export function applyCodePiecesToFlowModules( - codePieces: FlowModuleCodePieceElement[], - flowModules: FlowModule[] -): FlowModule[] { - const moduleCodePieces = new Map<string, FlowModuleCodePieceElement[]>() - for (const codePiece of codePieces) { - const moduleId = codePiece.id - if (!moduleCodePieces.has(moduleId)) { - moduleCodePieces.set(moduleId, []) - } - moduleCodePieces.get(moduleId)!.push(codePiece) - } - - // Clone modules to avoid mutation - const modifiedModules = JSON.parse(JSON.stringify(flowModules)) - - // Apply code pieces to each module - for (const [moduleId, pieces] of moduleCodePieces) { - const module = findModuleInModules(modifiedModules, moduleId) - if (module && module.value.type === 'rawscript' && module.value.content) { - module.value.content = applyCodePieceToCodeContext( - pieces as unknown as CodePieceElement[], - module.value.content - ) - } - } - - return modifiedModules -} - export function buildContextString(selectedContext: ContextElement[]): string { const dbTemplate = `- {title}: SCHEMA: \n{schema}\n` const codeTemplate = ` @@ -428,13 +387,7 @@ export function buildContextString(selectedContext: ContextElement[]): string { codeContext += codeTemplate .replace('{title}', context.title) .replace('{language}', scriptLangToEditorLang(context.lang)) - .replace( - '{code}', - applyCodePieceToCodeContext( - selectedContext.filter((c) => c.type === 'code_piece'), - context.content - ) - ) + .replace('{code}', context.content) } else if (context.type === 'error') { if (hasError) { throw new Error('Multiple error contexts provided') @@ -1000,6 +953,12 @@ async function callTool<T>({ `${functionName} is not available yet: no pipeline editor is open for this chat. Call open_preview(kind="pipeline", path="<folder>") first and wait for its result; once it reports the editor open, the pipeline tools are callable. Do not fall back to write_script.` ) } + // The MCP tools exist only in global mode and only while the user has a server + // turned on, a per-browser setting change_mode cannot reach. + if (/^(search_mcp_tools|call_mcp_(read|write)_tool)$/.test(functionName)) { + const server = typeof args?.server === 'string' ? args.server : undefined + throw new Error(await mcpUnavailableMessage(workspace, server)) + } throw new Error( `Unknown tool call: ${functionName}. Probably not in the correct mode, use the change_mode tool to switch to the correct mode.` ) diff --git a/frontend/src/lib/components/copilot/lib.ts b/frontend/src/lib/components/copilot/lib.ts index a0d890d643..0307641d6e 100644 --- a/frontend/src/lib/components/copilot/lib.ts +++ b/frontend/src/lib/components/copilot/lib.ts @@ -25,9 +25,11 @@ import { completionsRejectsToolsWithReasoning, explicitOffToken, requestsReasoning, + resolveRequestReasoning, stripLegacyThinkingSuffix, usesOpenAIResponsesApi, - type ReasoningEffort + type ReasoningEffort, + type ReasoningProviderModel } from './reasoningRegistry' import { formatResourceTypes } from './utils' import { @@ -604,6 +606,7 @@ interface AnthropicCompletionParams { resourcePath?: string resourceValue?: Record<string, any> maxTokensCap?: number + reasoningEffort?: ReasoningEffort info?: CopilotInfo } @@ -615,6 +618,7 @@ function buildAnthropicProxyRequest({ resourcePath, resourceValue, maxTokensCap, + reasoningEffort, info }: Omit<AnthropicCompletionParams, 'abortController'>) { const { system, messages: anthropicMessages } = convertOpenAIToAnthropicMessages(messages) @@ -633,12 +637,16 @@ function buildAnthropicProxyRequest({ ? workspaceAIClients.createAnthropicClient(workspace) : workspaceAIClients.getAnthropicClient() - const body = { - model: modelProvider.model, - max_tokens: resolveMaxTokens(modelProvider, maxTokensCap, undefined, info), - messages: anthropicMessages, - ...(system && { system }) - } + const body = applyReasoningToConfig( + { + model: modelProvider.model, + max_tokens: resolveMaxTokens(modelProvider, maxTokensCap, reasoningEffort, info), + messages: anthropicMessages, + ...(system && { system }) + }, + 'anthropic', + reasoningEffort + ) return { client, headers, body } } @@ -900,7 +908,7 @@ export function modelSupportsWebSearch(provider: AIProvider | undefined, model: } /** The model a request that names none sends: `info`'s workspace's default when given, else the - * tab's. */ + * last pick. */ function modelFor(info: CopilotInfo | undefined): AIProviderModel { return info ? resolveModelFor(info, undefined) : getCurrentModel() } @@ -1147,6 +1155,7 @@ export async function getCompletion( modelProvider, abortController, maxTokensCap: options?.maxTokensCap, + reasoningEffort: options?.reasoningEffort, workspace: options?.workspace, info: options?.info }) @@ -1224,7 +1233,11 @@ export async function getStreamedCompletionText( messages: ChatCompletionMessageParam[], abortController: AbortController, // `workspace` and `info` send it for that workspace, with its AI config, rather than the tab's. - options?: Partial<AiTarget> & { maxTokensCap?: number; forceModelProvider?: AIProviderModel } + options?: Partial<AiTarget> & { + maxTokensCap?: number + forceModelProvider?: AIProviderModel + reasoningEffort?: ReasoningEffort + } ): Promise<string> { const modelProvider = options?.forceModelProvider ?? modelFor(options?.info) const drain = async (forceCompletions: boolean) => { @@ -1232,6 +1245,7 @@ export async function getStreamedCompletionText( forceCompletions, forceModelProvider: modelProvider, maxTokensCap: options?.maxTokensCap, + reasoningEffort: options?.reasoningEffort, workspace: options?.workspace, info: options?.info }) @@ -1567,15 +1581,16 @@ export async function parseOpenAICompletion( } export function getResponseFromEvent(part: OpenAI.Chat.Completions.ChatCompletionChunk): string { - return part.choices?.[0]?.delta?.content || '' + return splitContentDelta(part.choices?.[0]?.delta?.content).text } export async function copilot( scriptOptions: CopilotOptions, generatedCode: Writable<string>, abortController: AbortController, - generatedExplanation?: Writable<string> + options?: { forceModelProvider?: ReasoningProviderModel; generatedExplanation?: Writable<string> } ) { + const { forceModelProvider, generatedExplanation } = options ?? {} const { prompt, systemPrompt } = await getPrompts(scriptOptions) const completion = await getCompletion( @@ -1589,7 +1604,12 @@ export async function copilot( content: prompt } ], - abortController + abortController, + undefined, + { + forceModelProvider, + reasoningEffort: forceModelProvider && resolveRequestReasoning(forceModelProvider) + } ) let response = '' @@ -1643,6 +1663,8 @@ export async function copilot( generatedCode.set(code) } } + // See `getStreamedCompletionText`: an aborted stream ends without throwing. + abortController.signal.throwIfAborted() // make sure we display the latest and complete code generatedCode.set(code) diff --git a/frontend/src/lib/components/copilot/scriptGenModel.dom.test.ts b/frontend/src/lib/components/copilot/scriptGenModel.dom.test.ts new file mode 100644 index 0000000000..0cf24c2546 --- /dev/null +++ b/frontend/src/lib/components/copilot/scriptGenModel.dom.test.ts @@ -0,0 +1,71 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { flushSync, mount, tick, unmount } from 'svelte' +import { get } from 'svelte/store' +import { + copilotSessionModel, + setCopilotInfo, + setLastModelPick, + setScriptGenModelPick +} from '$lib/aiStore' +import ScriptGen from './ScriptGen.svelte' +import { workspaceAIClients } from './lib' + +vi.mock('$app/navigation', () => ({ + goto: vi.fn(), + afterNavigate: vi.fn(), + beforeNavigate: vi.fn() +})) +// jsdom has no Element.animate. +vi.mock('svelte/transition', async (importOriginal) => ({ + ...(await importOriginal<typeof import('svelte/transition')>()), + fade: () => ({ duration: 0 }) +})) +vi.mock('monaco-editor', () => ({ Selection: class Selection {}, editor: {} })) + +let component: ReturnType<typeof mount> | undefined +afterEach(() => component && unmount(component)) + +it('sends its own model and effort, whatever the last pick is', async () => { + setCopilotInfo({ + providers: { + anthropic: { + resource_path: 'u/admin/a', + models: ['claude-sonnet-4-6', 'claude-opus-4-6', 'claude-opus-4-8'] + } + }, + default_model: { provider: 'anthropic', model: 'claude-sonnet-4-6' } + }) + const stream = vi.fn((_body: any) => + (async function* () { + yield { + type: 'content_block_delta', + delta: { type: 'text_delta', text: '```bash\necho\n```' } + } + })() + ) + vi.spyOn(workspaceAIClients, 'getAnthropicClient').mockReturnValue({ + messages: { stream } + } as any) + + component = mount(ScriptGen, { + target: document.body, + props: { lang: 'bash', editor: undefined, diffEditor: undefined, args: {} } + }) + const lastPick = { provider: 'anthropic', model: 'claude-opus-4-8' } as const + setLastModelPick(lastPick) + setScriptGenModelPick({ provider: 'anthropic', model: 'claude-opus-4-6', reasoning: 'low' }) + flushSync() + + document.querySelector<HTMLButtonElement>('button[title="Generate code from prompt"]')!.click() + await vi.waitFor(() => expect(document.querySelector('textarea')).toBeTruthy()) + const input = document.querySelector('textarea')! + input.value = 'say hi' + input.dispatchEvent(new Event('input', { bubbles: true })) + await tick() + input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })) + await vi.waitFor(() => expect(stream).toHaveBeenCalled()) + const body = stream.mock.calls[0][0] + expect(body.model).toBe('claude-opus-4-6') + expect(body.output_config?.effort).toBe('low') + expect(get(copilotSessionModel)).toEqual(lastPick) +}) diff --git a/frontend/src/lib/components/dbTableFilters.test.ts b/frontend/src/lib/components/dbTableFilters.test.ts index 7e914d2f2a..d02ee9241a 100644 --- a/frontend/src/lib/components/dbTableFilters.test.ts +++ b/frontend/src/lib/components/dbTableFilters.test.ts @@ -25,6 +25,12 @@ describe('dbColumnKind', () => { expect(dbColumnKind('bigint unsigned')).toBe('number') expect(dbColumnKind('bit')).toBe('boolean') }) + + it('matches arrays of numbers as text, which a number comparison cannot', () => { + expect(dbColumnKind('integer[]')).toBe('text') + expect(dbColumnKind('_int4')).toBe('text') + expect(dbColumnKind('ARRAY<INT64>')).toBe('text') + }) }) describe('renderColumnFilter', () => { @@ -38,10 +44,13 @@ describe('renderColumnFilter', () => { expect(renderColumnFilter('name', 'varchar', '=Bob', 'mysql')).toBe("`name` = 'Bob'") }) - it('compares PostgreSQL json as text for an exact match', () => { + it('compares PostgreSQL json and arrays as text for an exact match', () => { expect(renderColumnFilter('js', 'json', '={"a": 1}', 'postgresql')).toBe( `CAST("js" AS TEXT) = '{"a": 1}'` ) + expect(renderColumnFilter('tags', 'integer[]', '=4999', 'postgresql')).toBe( + `CAST("tags" AS TEXT) = '4999'` + ) }) it('serializes BigQuery complex columns, which have no cast to STRING', () => { @@ -80,4 +89,9 @@ describe('renderDbTableFilters', () => { ) ).toBe(`(contains(lower(CAST("first name" AS VARCHAR)), 'al b')) AND ("id" = 2)`) }) + + it('keeps letters of any script in a key', () => { + const schema = buildDbTableFilterSchema([col('ünïcødé 名前', 'text')]) + expect(schema.keyOfColumn['ünïcødé 名前']).toBe('ünïcødé_名前') + }) }) diff --git a/frontend/src/lib/components/dbTableFilters.ts b/frontend/src/lib/components/dbTableFilters.ts index c3266b3ac7..a816c1dceb 100644 --- a/frontend/src/lib/components/dbTableFilters.ts +++ b/frontend/src/lib/components/dbTableFilters.ts @@ -30,8 +30,16 @@ const NUMERIC_TYPE = /^(u?(tiny|small|medium|big|huge)?int(eger)?\d*|(small|big)?serial\d*|numeric|decimal|dec|float\d*|double|real|number|money|smallmoney|bignumeric)\b/ const BOOLEAN_TYPE = /^(bool|boolean|bit)\b/ +/** `integer[]`, Postgres's `_int4`, `ARRAY<INT64>`. */ +function isArrayType(datatype: string | undefined): boolean { + const t = (datatype ?? '').trim().toLowerCase() + return t.endsWith(']') || t.startsWith('_') || t.startsWith('array') +} + export function dbColumnKind(datatype: string | undefined): DbColumnKind { const t = (datatype ?? '').trim().toLowerCase() + // An array of numbers is matched as text, not compared. + if (isArrayType(t)) return 'text' if (NUMERIC_TYPE.test(t)) return 'number' if (BOOLEAN_TYPE.test(t)) return 'boolean' return 'text' @@ -41,8 +49,8 @@ const NUMERIC_FILTER = /^(>=|<=|!=|<>|>|<|=)?\s*(-?\d+(\.\d+)?([eE][+-]?\d+)?)$/ export type DbTableFilterSchema = { schema: FilterSchemaRec - /** Search bar key → column name. The bar only recognises `\w+` keys, so - * other column names get a sanitized key. */ + /** Search bar key → column name. A key is letters, digits and `_`, so other + * column names get a sanitized key. */ columnOfKey: Record<string, string> keyOfColumn: Record<string, string> } @@ -53,7 +61,7 @@ export function buildDbTableFilterSchema(columns: ColumnDef[]): DbTableFilterSch const keyOfColumn: Record<string, string> = {} for (const col of columns) { if (!col.field || col.filterable === false) continue - let base = col.field.replace(/\W+/g, '_') || 'column' + let base = col.field.replace(/[^\p{L}\p{N}_]+/gu, '_') || 'column' if (base === FREE_TEXT_KEY) base = `${base}col` let key = base for (let i = 2; key in schema; i++) key = `${base}_${i}` @@ -121,8 +129,12 @@ export function renderColumnFilter( : `STRPOS(LOWER(${serialized}), ${renderDbLiteral(text.toLowerCase(), dbType)}) > 0` } if (!text.startsWith('=')) return renderDbContainsFilter(column, text, dbType) - // PostgreSQL `json` has no `=`: compare as the text the grid shows. - if (dbType === 'postgresql' && /^jsonb?$/i.test((datatype ?? '').trim())) { + // PostgreSQL `json` has no `=`, and an array would read the value as an array + // literal and fail on any other text: compare as the text the grid shows. + if ( + dbType === 'postgresql' && + (/^jsonb?$/i.test((datatype ?? '').trim()) || isArrayType(datatype)) + ) { const literal = renderDbLiteral(text.slice(1), dbType)! return `CAST(${renderDbQuotedIdentifier(column, dbType)} AS TEXT) = ${literal}` } diff --git a/frontend/src/lib/components/dbTableLayoutStorage.ts b/frontend/src/lib/components/dbTableLayoutStorage.ts index 75e5c78b59..e4d95af5ac 100644 --- a/frontend/src/lib/components/dbTableLayoutStorage.ts +++ b/frontend/src/lib/components/dbTableLayoutStorage.ts @@ -14,6 +14,8 @@ export type DbTableLayout = { /** Columns left out of the grid. */ hidden?: string[] formats?: Record<string, ColumnFormat> + /** `widths` leave room for the header's filter button. */ + widthsFitFilterButton?: boolean lastUsed?: number } diff --git a/frontend/src/lib/components/dbt/DbtEditor.svelte b/frontend/src/lib/components/dbt/DbtEditor.svelte index 7a93d7c5e7..f1a082a49c 100644 --- a/frontend/src/lib/components/dbt/DbtEditor.svelte +++ b/frontend/src/lib/components/dbt/DbtEditor.svelte @@ -65,6 +65,7 @@ modules = $bindable(), editor = $bindable(), path, + storagePath = undefined, tag, timeout = undefined, customUi = undefined, @@ -80,6 +81,8 @@ modules?: { [key: string]: ScriptModule } | null editor?: Editor | undefined path: string | undefined + /** Where the script's draft is stored, which a new or renamed script's `path` is not. */ + storagePath?: string tag: string | undefined timeout?: number customUi?: ScriptEditorWhitelabelCustomUi | undefined @@ -509,6 +512,12 @@ lineNumbersMinChars={4} folding {path} + codeSource={{ + kind: 'script', + path: storagePath || path || '', + part: openFile ?? undefined + }} + codeSourceLang="dbt" bind:code={editorCode} bind:this={editor} on:change={() => { diff --git a/frontend/src/lib/components/debug/debugUtils.ts b/frontend/src/lib/components/debug/debugUtils.ts index b9b9c9b174..d57fef203a 100644 --- a/frontend/src/lib/components/debug/debugUtils.ts +++ b/frontend/src/lib/components/debug/debugUtils.ts @@ -4,6 +4,7 @@ */ import { VariableService, UserService } from '$lib/gen' +import { needsSuperAdminFor } from '$lib/stores' /** * Fetch contextual variables (WM_WORKSPACE, WM_TOKEN, etc.) for the debugger. @@ -28,7 +29,10 @@ export async function fetchContextualVariables(workspace: string): Promise<Recor requestBody: { label: 'debugger-token', expiration: expirationDate.toISOString(), - workspace_id: workspace + workspace_id: workspace, + // Stands in for the job's own WM_TOKEN, which carries the user's admin rights. + admin: true, + super_admin: needsSuperAdminFor(workspace) } }) envVars['WM_TOKEN'] = freshToken diff --git a/frontend/src/lib/components/deploymentRequest/AiReview.svelte b/frontend/src/lib/components/deploymentRequest/AiReview.svelte index 5628962dbc..7dc73e5e8e 100644 --- a/frontend/src/lib/components/deploymentRequest/AiReview.svelte +++ b/frontend/src/lib/components/deploymentRequest/AiReview.svelte @@ -2,12 +2,14 @@ import { Alert, Badge, Button } from '$lib/components/common' import type { AIProviderModel } from '$lib/gen' import { + aiReviewModel, copilotInfo, - copilotSessionModel, + setAiReviewModelPick, tryResolveModelFor, type CopilotInfo } from '$lib/aiStore' - import Select from '$lib/components/select/Select.svelte' + import ProviderModelSelector from '$lib/components/copilot/chat/ProviderModelSelector.svelte' + import type { ReasoningProviderModel } from '$lib/components/copilot/reasoningRegistry' import { sendUserToast } from '$lib/toast' import { logFeatureUsage } from '$lib/utils/featureUsage' import { Loader2, MessageSquarePlus, Sparkles, WandSparkles, X } from 'lucide-svelte' @@ -44,8 +46,8 @@ onPost?: (finding: AiReviewFinding) => Promise<void> /** The reviewed workspace's AI config, when it is not the tab's (an AI session's). */ info?: CopilotInfo - /** The model to start on instead of the last pick (an AI session's own). */ - defaultModel?: AIProviderModel + /** The model to start on instead of the review's own pick or the workspace default (an AI session's own). */ + defaultModel?: ReasoningProviderModel } let { scope, source, onPost, info, defaultModel }: Props = $props() @@ -71,14 +73,23 @@ let stale = $derived(reviewed != undefined && reviewed.key !== itemsKey(items)) const modelKey = (m: AIProviderModel) => `${m.provider}:${m.model}` - // Local to this review: picking a model here must not change the chat's own selection, - // which is only the default until something is picked. - let pickedModelKey = $state<string | undefined>(undefined) + // Neither follows nor sets the sessions' last pick. Outside a session the pick is remembered for + // the next review; inside one it stays local to this review. + let picked = $state<ReasoningProviderModel | undefined>(undefined) let aiModels = $derived((info ?? $copilotInfo).aiModels) - let chatModel = $derived( - defaultModel ?? tryResolveModelFor(info ?? $copilotInfo, $copilotSessionModel) + let startModel = $derived( + defaultModel ?? tryResolveModelFor(info ?? $copilotInfo, $aiReviewModel) ) - let selectedModelKey = $derived(pickedModelKey ?? (chatModel && modelKey(chatModel))) + // A pick the reviewed workspace no longer offers gives way to the model the review started on. + let model = $derived.by(() => { + const pick = picked + return pick && aiModels.some((m) => modelKey(m) === modelKey(pick)) ? pick : startModel + }) + + function pickModel(pick: ReasoningProviderModel) { + picked = pick + if (!defaultModel) setAiReviewModelPick(pick) + } async function run() { abortController?.abort() @@ -91,7 +102,7 @@ logFeatureUsage('deployment_request', 'ai_review', { key: source }) try { const review = await reviewChanges(scope, controller, { - model: aiModels.find((m) => modelKey(m) === selectedModelKey), + model, info }) if (!controller.signal.aborted) result = review @@ -217,14 +228,8 @@ > {result ? 'Review again with AI' : 'Review with AI'} </Button> - {#if aiModels.length > 1} - <div class="w-56"> - <Select - size="sm" - items={aiModels.map((m) => ({ label: m.model, value: modelKey(m) }))} - bind:value={() => selectedModelKey, (v) => (pickedModelKey = v)} - /> - </div> + {#if model} + <ProviderModelSelector {model} onPick={pickModel} models={aiModels} /> {/if} {#if items.length === 0} <span class="text-xs text-secondary"> diff --git a/frontend/src/lib/components/deploymentRequest/aiReview.test.ts b/frontend/src/lib/components/deploymentRequest/aiReview.test.ts index 559164a5a3..e2d9a9f56f 100644 --- a/frontend/src/lib/components/deploymentRequest/aiReview.test.ts +++ b/frontend/src/lib/components/deploymentRequest/aiReview.test.ts @@ -5,20 +5,22 @@ const h = vi.hoisted(() => ({ prompt: '', system: '', workspace: '' as string | undefined, + reasoningEffort: undefined as string | undefined, reads: 0, instructionReads: [] as string[], listed: [] as string[] })) vi.mock('$lib/components/copilot/lib', () => ({ - getNonStreamingCompletion: async ( + getStreamedCompletionText: async ( messages: { content: string }[], _abort: AbortController, - options?: { workspace?: string } + options?: { workspace?: string; reasoningEffort?: string } ) => { h.system = messages[0].content h.prompt = messages[1].content h.workspace = options?.workspace + h.reasoningEffort = options?.reasoningEffort return '{"summary":"s","findings":[]}' } })) @@ -150,4 +152,19 @@ describe('drafts review', () => { expect(h.workspace).toBe('parent') expect(h.system).toContain('You review drafts in a Windmill workspace') }) + + it('sends the effort picked with the model', async () => { + await reviewChanges( + { + kind: 'drafts', + workspaceId: 'parent', + items: [ + { kind: 'script', path: 'f/a/b', change: 'added', load: async () => ({ after: 'x' }) } + ] + }, + new AbortController(), + { model: { provider: 'anthropic', model: 'claude-sonnet-4-6', reasoning: 'low' } } + ) + expect(h.reasoningEffort).toBe('low') + }) }) diff --git a/frontend/src/lib/components/deploymentRequest/aiReview.ts b/frontend/src/lib/components/deploymentRequest/aiReview.ts index a930044ef2..f8f94a9e71 100644 --- a/frontend/src/lib/components/deploymentRequest/aiReview.ts +++ b/frontend/src/lib/components/deploymentRequest/aiReview.ts @@ -1,6 +1,10 @@ -import type { AIProviderModel, WorkspaceItemDiff } from '$lib/gen' +import type { WorkspaceItemDiff } from '$lib/gen' import type { CopilotInfo } from '$lib/aiStore' -import { getNonStreamingCompletion } from '$lib/components/copilot/lib' +import { getStreamedCompletionText } from '$lib/components/copilot/lib' +import { + resolveRequestReasoning, + type ReasoningProviderModel +} from '$lib/components/copilot/reasoningRegistry' import { getItemValue } from '$lib/utils_workspace_deploy' import type { Kind } from '$lib/utils_deployable' import { @@ -9,7 +13,6 @@ import { } from '$lib/components/copilot/chat/folderInstructions' import { instructionsCovering, - MAX_OUTPUT_TOKENS, parseReviewAnswer, renderItemValue, REVIEW_INSTRUCTIONS_RESOURCE_TYPE, @@ -186,8 +189,8 @@ export async function reviewChanges( scope: ReviewScope, abortController: AbortController, options?: { - /** Defaults to the workspace default of `info`, or without it to the last pick. */ - model?: AIProviderModel + /** Defaults to the workspace default of `info`. Without either, the last pick is sent. */ + model?: ReasoningProviderModel /** The reviewed workspace's AI config, when it is not the tab's. */ info?: CopilotInfo } @@ -220,7 +223,7 @@ export async function reviewChanges( const instructions = await instructionsPromise if (abortController.signal.aborted) throw new Error('aborted') - const answer = await getNonStreamingCompletion( + const answer = await getStreamedCompletionText( [ { role: 'system', content: reviewSystemPrompt(subject) + instructions.text }, { @@ -236,8 +239,8 @@ export async function reviewChanges( // Bound to the reviewed workspace: without `workspace` the call goes through whichever // workspace the app has switched to by the time the item reads finish. { - maxTokensCap: MAX_OUTPUT_TOKENS, forceModelProvider: options?.model, + reasoningEffort: options?.model && resolveRequestReasoning(options.model), workspace: workspaceId, info: options?.info } diff --git a/frontend/src/lib/components/flows/FlowProgressBar.svelte b/frontend/src/lib/components/flows/FlowProgressBar.svelte index 8b3a966d57..61c320ac53 100644 --- a/frontend/src/lib/components/flows/FlowProgressBar.svelte +++ b/frontend/src/lib/components/flows/FlowProgressBar.svelte @@ -4,6 +4,8 @@ import { forLater } from '$lib/forLater' import { waitingRequest } from '../agentRequest' import type { Snippet } from 'svelte' + import type { GraphModuleState } from '../graph' + import { displayDate } from '$lib/utils' interface Props { job?: Job | undefined @@ -13,7 +15,11 @@ textPosition?: 'top' | 'bottom' // Prefer step ID over step index when both are available showStepId?: boolean + /** The run graph's step states, which say why a step that has not started is waiting. */ + stepStates?: Record<string, GraphModuleState> errorAction?: Snippet + /** A run nested under this one waits on an approval, which its own steps don't show. */ + waitingNested?: boolean } let { @@ -23,9 +29,42 @@ slim = false, textPosition = 'top', showStepId = false, - errorAction + stepStates = undefined, + errorAction, + waitingNested = false }: Props = $props() + // The current step, or a step waiting inside it when it is a subflow. + let waitingText = $derived.by(() => { + const current = job?.flow_status?.modules?.[job.flow_status.step]?.id + if (!current || !stepStates) return undefined + const inside = `subflow:${current}:` + const retrying = Object.entries(stepStates).find( + ([key, s]) => + (key === current || key.startsWith(inside)) && + (s.type === 'WaitingForExecutor' || s.type === 'InProgress') && + (s.retries ?? 0) > 0 + ) + if (retrying) { + const [key, s] = retrying + const n = s.retries ?? 0 + return `Retrying step '${key.split(':').pop()}', ${n} failed attempt${n === 1 ? '' : 's'}` + } + const found = Object.entries(stepStates).find( + ([key, s]) => + (key === current || key.startsWith(inside)) && + s.type === 'WaitingForExecutor' && + s.waiting_reason + ) + if (!found) return undefined + const [key, s] = found + const step = key.split(':').pop() + const until = displayDate(s.scheduled_for, true) + return s.waiting_reason === 'sleep' + ? `Sleeping before step '${step}' until ${until}` + : `Step '${step}' held by concurrency limit, next check by ${until}` + }) + let error: number | undefined = $state(undefined) let index = $state(0) let subIndex: number | undefined = $state(undefined) @@ -189,9 +228,10 @@ {textPosition} stepId={currentStepId} {showStepId} - {isWaitingForEvents} + isWaitingForEvents={isWaitingForEvents || waitingNested} {isCanceled} {isScheduled} {isSkipped} + {waitingText} {errorAction} /> diff --git a/frontend/src/lib/components/flows/content/FailureThresholdSetting.svelte b/frontend/src/lib/components/flows/content/FailureThresholdSetting.svelte new file mode 100644 index 0000000000..725e12e190 --- /dev/null +++ b/frontend/src/lib/components/flows/content/FailureThresholdSetting.svelte @@ -0,0 +1,108 @@ +<script lang="ts"> + import { getContext } from 'svelte' + import type { FlowModule, ForloopFlow, WhileloopFlow } from '$lib/gen' + import type { FlowEditorContext } from '../types' + import Toggle from '$lib/components/Toggle.svelte' + import SimpleEditor from '$lib/components/SimpleEditor.svelte' + import InputTransformForm from '$lib/components/InputTransformForm.svelte' + import PropPickerWrapper from '../propPicker/PropPickerWrapper.svelte' + import { getStepPropPicker } from '../previousResults' + import { emptySchema } from '$lib/utils' + + interface Props { + mod: FlowModule + parentModule: FlowModule | undefined + previousModule: FlowModule | undefined + tooltip: string + documentationLink: string + } + + let { + mod = $bindable(), + parentModule, + previousModule, + tooltip, + documentationLink + }: Props = $props() + + const { previewArgs, flowStateStore, flowStore } = + getContext<FlowEditorContext>('FlowEditorContext') + + const DEFAULT_THRESHOLD = 5 + + let editor: SimpleEditor | undefined = $state(undefined) + let schema = $state(emptySchema()) + schema.properties['failure_threshold'] = { type: 'integer' } + + const loop = () => mod.value as ForloopFlow | WhileloopFlow + + // The worker also takes a bare number, which the form cannot edit. + if (typeof loop().failure_threshold === 'number') { + loop().failure_threshold = { type: 'static', value: loop().failure_threshold } + } + + let stepPropPicker = $derived( + getStepPropPicker( + flowStateStore.val, + parentModule, + previousModule, + mod.id, + flowStore.val, + previewArgs.val, + false + ) + ) + + const enabled = $derived(loop().failure_threshold != undefined) + // The form seeds its static/expression mode once, so a threshold that appears needs a fresh + // form; one that is removed must not remount it, or the header shows twice while it slides out. + let appearances = 0 + let wasEnabled = false + const formKey = $derived.by(() => { + if (enabled && !wasEnabled) appearances++ + wasEnabled = enabled + return appearances + }) +</script> + +{#snippet header()} + <Toggle + size="xs" + textClass="text-xs font-normal text-primary" + checked={enabled} + on:change={({ detail }) => { + loop().failure_threshold = detail ? { type: 'static', value: DEFAULT_THRESHOLD } : undefined + }} + options={{ + right: 'Limit failed iterations', + rightTooltip: tooltip, + rightDocumentationLink: documentationLink + }} + /> +{/snippet} + +<PropPickerWrapper + sidePane + flow_input={stepPropPicker.pickableProperties.flow_input} + notSelectable + pickableProperties={stepPropPicker.pickableProperties} + on:select={({ detail }) => { + editor?.insertAtCursor(detail) + editor?.focus() + }} +> + {#key formKey} + <InputTransformForm + bind:arg={() => loop().failure_threshold, (v) => (loop().failure_threshold = v)} + argName="failure_threshold" + collapsed={!enabled} + {header} + {schema} + argExtra={{ min: 1, step: 1 }} + extraLib={stepPropPicker.extraLib} + animateAppear + previousModuleId={previousModule?.id} + bind:editor + /> + {/key} +</PropPickerWrapper> diff --git a/frontend/src/lib/components/flows/content/FlowLoop.svelte b/frontend/src/lib/components/flows/content/FlowLoop.svelte index 7b9933d5e0..b0bcbea290 100644 --- a/frontend/src/lib/components/flows/content/FlowLoop.svelte +++ b/frontend/src/lib/components/flows/content/FlowLoop.svelte @@ -19,6 +19,7 @@ import { logIterationLabel } from '../iterationLabelTelemetry' import InputTransformForm from '$lib/components/InputTransformForm.svelte' + import FailureThresholdSetting from './FailureThresholdSetting.svelte' import PropPickerWrapper from '../propPicker/PropPickerWrapper.svelte' import type { PropPickerContext } from '$lib/components/prop_picker' import { useUiIntent } from '$lib/components/copilot/chat/flow/useUiIntent' @@ -178,6 +179,8 @@ 'The JavaScript expression that will be evaluated to get the list of items to iterate over. Example: ["banana", "apple", flow_input.my_fruit].' const ITERATION_LABEL_TOOLTIP = 'Evaluated for each iteration to name it in the run viewer and the iteration picker, e.g. flow_input.iter.value.name. A failing expression only leaves the iteration unnamed.' + const FAILURE_THRESHOLD_TOOLTIP = + 'Fail the loop, and the flow with it, once this many iterations have failed. A number, or an expression evaluated when the loop starts, e.g. Math.ceil(flow_input.targets.length * 0.1). A parallel loop cancels the iterations not started yet, including those held back by the concurrency limit, and lets the running ones finish: limit concurrent iterations to bound how many are running at that point.' const DEFAULT_PARALLELISM = 4 const PARALLELISM_LABEL = 'Limit concurrent iterations' const SQUASH_PARALLEL_CONFLICT = @@ -321,17 +324,33 @@ </PropPickerWrapper> </section> <section class="flex flex-col gap-6"> - <Toggle - size="xs" - textClass="text-xs font-normal text-primary" - bind:checked={mod.value.skip_failures} - options={{ - right: 'Skip failures', - rightTooltip: - 'If disabled, the flow will fail as soon as one of the iteration fail. Otherwise, the error will be collected as the result of the iteration. Regardless of this setting, if a flow level error handler is defined, it will process the error. (Workspace error handlers will NOT be used to process errors if enabled.)', - rightDocumentationLink: 'https://www.windmill.dev/docs/flows/flow_loops' - }} - /> + <div class="flex flex-col gap-2"> + <Toggle + size="xs" + textClass="text-xs font-normal text-primary" + bind:checked={mod.value.skip_failures} + on:change={({ detail }) => { + if (!detail) (mod.value as ForloopFlow).failure_threshold = undefined + }} + options={{ + right: 'Skip failures', + rightTooltip: + 'If disabled, the flow will fail as soon as one of the iteration fail. Otherwise, the error will be collected as the result of the iteration. Regardless of this setting, if a flow level error handler is defined, it will process the error. (Workspace error handlers will NOT be used to process errors if enabled.)', + rightDocumentationLink: 'https://www.windmill.dev/docs/flows/flow_loops' + }} + /> + {#if mod.value.skip_failures} + <div class="pl-9" transition:slideDynamic> + <FailureThresholdSetting + bind:mod + {parentModule} + {previousModule} + tooltip={FAILURE_THRESHOLD_TOOLTIP} + documentationLink="https://www.windmill.dev/docs/flows/flow_loops" + /> + </div> + {/if} + </div> <Toggle size="xs" textClass="text-xs font-normal text-primary" diff --git a/frontend/src/lib/components/flows/content/FlowModuleComponent.svelte b/frontend/src/lib/components/flows/content/FlowModuleComponent.svelte index 7d22c1d1c3..294bd09b54 100644 --- a/frontend/src/lib/components/flows/content/FlowModuleComponent.svelte +++ b/frontend/src/lib/components/flows/content/FlowModuleComponent.svelte @@ -1,4 +1,5 @@ <script lang="ts"> + import type { CodeSource } from '$lib/components/copilot/chat/context' import HostWindow from '$lib/components/common/HostWindow.svelte' import { Pane, Splitpanes } from 'svelte-splitpanes' import { refreshStateStore } from '$lib/svelte5Utils.svelte' @@ -170,6 +171,15 @@ siblingToolNames = undefined }: Props = $props() + // Withheld where the toolbar's own AI button is. + const codeSource = $derived.by((): CodeSource | undefined => { + if (customUi?.editorBar?.aiGen == false) return undefined + const agent = agentEditorHost?.() + return agent !== undefined + ? { kind: 'agent', path: agent, part: flowModule.id } + : { kind: 'flow', path: $pathStore, part: flowModule.id } + }) + const DEFAULT_BACKGROUND_AFTER_SECS = 30 type BackgroundMode = 'never' | 'after' | 'always' let backgroundMode: BackgroundMode = $derived( @@ -1055,7 +1065,7 @@ {} )} key={`flow-inline-${opWs}-${$pathStore}-${flowModule.id}`} - moduleId={flowModule.id} + {codeSource} preparedAssetsSqlQueries={preparedSqlQueries.current} customTag={flowModule.value.tag} /> @@ -1116,7 +1126,7 @@ {} )} key={`flow-inline-${opWs}-${$pathStore}-${flowModule.id}`} - moduleId={flowModule.id} + {codeSource} preparedAssetsSqlQueries={preparedSqlQueries.current} customTag={flowModule.value.tag} /> diff --git a/frontend/src/lib/components/flows/content/FlowModuleSuspend.svelte b/frontend/src/lib/components/flows/content/FlowModuleSuspend.svelte index 95b9ae4ef5..ba1f58b584 100644 --- a/frontend/src/lib/components/flows/content/FlowModuleSuspend.svelte +++ b/frontend/src/lib/components/flows/content/FlowModuleSuspend.svelte @@ -178,6 +178,22 @@ </span> </Label> + <Toggle + size="xs" + textClass="text-xs font-normal text-primary" + disabled={!flowModule.suspend} + checked={Boolean(flowModule.suspend?.show_on_home)} + options={{ + right: "List on approvers' home", + rightTooltip: + 'A run waiting on this step shows on the home page of everyone who can approve it. Leave off when the request is sent through Slack, Discord or email.' + }} + on:change={(e) => { + if (flowModule.suspend) { + flowModule.suspend.show_on_home = e.detail + } + }} + /> <Toggle size="xs" textClass="text-xs font-normal text-primary" diff --git a/frontend/src/lib/components/flows/content/FlowWhileLoop.svelte b/frontend/src/lib/components/flows/content/FlowWhileLoop.svelte index ee4de427ec..ac204fe8cd 100644 --- a/frontend/src/lib/components/flows/content/FlowWhileLoop.svelte +++ b/frontend/src/lib/components/flows/content/FlowWhileLoop.svelte @@ -16,6 +16,7 @@ import TextInput from '$lib/components/text_input/TextInput.svelte' import { SecondsInput } from '$lib/components/common' import { slideDynamic } from '$lib/transitions' + import FailureThresholdSetting from './FailureThresholdSetting.svelte' const { flowStateStore } = getContext<FlowEditorContext>('FlowEditorContext') @@ -189,17 +190,33 @@ {/if} </div> - <Toggle - size="xs" - textClass="text-xs font-normal text-primary" - bind:checked={mod.value.skip_failures} - options={{ - right: 'Skip failures', - rightTooltip: - 'If disabled, the flow will fail as soon as one of the iteration fail. Otherwise, the error will be collected as the result of the iteration. Regardless of this setting, if a flow level error handler is defined, it will process the error. (Workspace error handlers will NOT be used to process errors if enabled.)', - rightDocumentationLink: 'https://www.windmill.dev/docs/flows/while_loops' - }} - /> + <div class="flex flex-col gap-2"> + <Toggle + size="xs" + textClass="text-xs font-normal text-primary" + bind:checked={mod.value.skip_failures} + on:change={({ detail }) => { + if (!detail) (mod.value as WhileloopFlow).failure_threshold = undefined + }} + options={{ + right: 'Skip failures', + rightTooltip: + 'If disabled, the flow will fail as soon as one of the iteration fail. Otherwise, the error will be collected as the result of the iteration. Regardless of this setting, if a flow level error handler is defined, it will process the error. (Workspace error handlers will NOT be used to process errors if enabled.)', + rightDocumentationLink: 'https://www.windmill.dev/docs/flows/while_loops' + }} + /> + {#if mod.value.skip_failures} + <div class="pl-9" transition:slideDynamic> + <FailureThresholdSetting + bind:mod + {parentModule} + {previousModule} + tooltip="Fail the loop, and the flow with it, once this many iterations have failed. A number, or an expression evaluated when the loop starts." + documentationLink="https://www.windmill.dev/docs/flows/while_loops" + /> + </div> + {/if} + </div> <Toggle size="xs" textClass="text-xs font-normal text-primary" diff --git a/frontend/src/lib/components/flows/content/McpToolEditor.svelte b/frontend/src/lib/components/flows/content/McpToolEditor.svelte index 18d69dcb63..edea884c7a 100644 --- a/frontend/src/lib/components/flows/content/McpToolEditor.svelte +++ b/frontend/src/lib/components/flows/content/McpToolEditor.svelte @@ -32,6 +32,7 @@ import type { FlowEditorContext } from '../types' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' import Toggle from '$lib/components/Toggle.svelte' + import { hasListedMcpTools, rememberListedMcpTools } from './mcpToolsConsent' const operatingWorkspace = useOperatingWorkspace() @@ -62,13 +63,28 @@ let resourcePath = $derived(tool.value.resource_path) let error = $derived(tools.error?.body?.message || tools.error?.message) + let listedVersion = $state(0) + let mayList = $derived.by(() => { + listedVersion + return !!opWs && resourcePath?.length > 0 && hasListedMcpTools(opWs, resourcePath) + }) + + function allowListing(path: string | undefined) { + if (!opWs || !path) return + rememberListedMcpTools(opWs, path) + listedVersion += 1 + } + $effect(() => { resourcePath opWs refreshCount + const allowed = mayList untrack(() => { - if (resourcePath?.length > 0) { + if (allowed) { tools.refresh() + } else { + tools.clear() } }) }) @@ -90,6 +106,7 @@ async function handleOAuthConnected(resourcePath: string, resourceName: string) { await resourcePicker?.refreshResources() + allowListing(resourcePath) tool.value.resource_path = resourcePath tool.summary = `MCP: ${resourceName}` } @@ -105,6 +122,7 @@ placeholder="Select an MCP resource" bind:value={tool.value.resource_path} workspace={opWs} + onValueChange={(path) => allowListing(path)} /> </Label> </div> @@ -146,7 +164,10 @@ <Button size="xs" color="light" - onClick={() => (refreshCount += 1)} + onClick={() => { + allowListing(resourcePath) + refreshCount += 1 + }} startIcon={{ icon: RefreshCw }} disabled={tools.status === 'loading'} > diff --git a/frontend/src/lib/components/flows/content/StepIdBadge.svelte b/frontend/src/lib/components/flows/content/StepIdBadge.svelte index 9594ac6f83..4d37b202a6 100644 --- a/frontend/src/lib/components/flows/content/StepIdBadge.svelte +++ b/frontend/src/lib/components/flows/content/StepIdBadge.svelte @@ -3,9 +3,13 @@ interface Props { id: string + /** Past this many characters, cut from the start: the end of a chained id is the step. */ + maxLength?: number } - let { id }: Props = $props() + let { id, maxLength }: Props = $props() + + let shown = $derived(maxLength && id.length > maxLength ? '…' + id.slice(1 - maxLength) : id) </script> <!-- Styled like the id badge on a graph node, so a step named in text reads as the same thing. --> @@ -16,5 +20,5 @@ baseClass="!px-1" title={id} > - <span class="text-2xs font-normal">{id}</span> + <span class="text-2xs font-normal">{shown}</span> </Badge> diff --git a/frontend/src/lib/components/flows/content/mcpToolsConsent.test.ts b/frontend/src/lib/components/flows/content/mcpToolsConsent.test.ts new file mode 100644 index 0000000000..383c54201c --- /dev/null +++ b/frontend/src/lib/components/flows/content/mcpToolsConsent.test.ts @@ -0,0 +1,21 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +describe('mcpToolsConsent', () => { + beforeEach(() => { + localStorage.clear() + vi.resetModules() + }) + + it('lists automatically only for a resource listed at the user request, per workspace', async () => { + const { hasListedMcpTools, rememberListedMcpTools } = await import('./mcpToolsConsent') + expect(hasListedMcpTools('ws', 'u/other/mcp')).toBe(false) + rememberListedMcpTools('ws', 'f/team/mcp') + expect(hasListedMcpTools('ws', 'f/team/mcp')).toBe(true) + expect(hasListedMcpTools('other_ws', 'f/team/mcp')).toBe(false) + + // Survives a reload, so reopening a saved step lists its tools again. + vi.resetModules() + const reloaded = await import('./mcpToolsConsent') + expect(reloaded.hasListedMcpTools('ws', 'f/team/mcp')).toBe(true) + }) +}) diff --git a/frontend/src/lib/components/flows/content/mcpToolsConsent.ts b/frontend/src/lib/components/flows/content/mcpToolsConsent.ts new file mode 100644 index 0000000000..2b8ffea64b --- /dev/null +++ b/frontend/src/lib/components/flows/content/mcpToolsConsent.ts @@ -0,0 +1,40 @@ +/** + * MCP resources whose tools this browser has listed at the user's request. + * + * Listing tools connects to the URL the resource names and sends it the secrets the + * resource references, resolved as the viewer. A step's resource path can come from a + * flow the viewer did not write (a shared link's hash, a colleague's flow), so the tool + * panel lists automatically only for a resource the viewer picked or listed before. + */ +const STORAGE_KEY = 'mcpToolsListedResources' +const MAX_ENTRIES = 500 + +function key(workspace: string, path: string): string { + return `${workspace}:${path}` +} + +function read(): string[] { + try { + const parsed = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '[]') + return Array.isArray(parsed) ? parsed.filter((e) => typeof e === 'string') : [] + } catch { + return [] + } +} + +const sessionListed = new Set<string>() + +export function hasListedMcpTools(workspace: string, path: string): boolean { + const k = key(workspace, path) + return sessionListed.has(k) || read().includes(k) +} + +export function rememberListedMcpTools(workspace: string, path: string): void { + const k = key(workspace, path) + sessionListed.add(k) + try { + const entries = read().filter((e) => e !== k) + entries.push(k) + localStorage.setItem(STORAGE_KEY, JSON.stringify(entries.slice(-MAX_ENTRIES))) + } catch {} +} diff --git a/frontend/src/lib/components/flows/map/FlowModuleSchemaItem.svelte b/frontend/src/lib/components/flows/map/FlowModuleSchemaItem.svelte index 2c468d9773..5e960ad82d 100644 --- a/frontend/src/lib/components/flows/map/FlowModuleSchemaItem.svelte +++ b/frontend/src/lib/components/flows/map/FlowModuleSchemaItem.svelte @@ -66,6 +66,8 @@ pathHref?: string nodeState?: FlowNodeState retries?: number | undefined + /** In a run, while its concurrency limit holds the step back. */ + held?: { since?: string; nextCheck?: Date | string } /** In a run, the attempts the retry badge picks from. */ attempts?: RetryAttempts | undefined warningMessage?: string | undefined @@ -101,6 +103,7 @@ pathHref = undefined, nodeState, retries = undefined, + held = undefined, attempts = undefined, warningMessage = undefined, editMode = false, @@ -311,6 +314,7 @@ <StepSettingsBar {settings} {retries} + {held} {attempts} onOpenChange={(o) => (settingsMenuOpen = o)} onOpenSetting={editMode && id diff --git a/frontend/src/lib/components/flows/map/FlowModuleSchemaMap.svelte b/frontend/src/lib/components/flows/map/FlowModuleSchemaMap.svelte index e7e1dcf96c..b7f9a85ab2 100644 --- a/frontend/src/lib/components/flows/map/FlowModuleSchemaMap.svelte +++ b/frontend/src/lib/components/flows/map/FlowModuleSchemaMap.svelte @@ -116,6 +116,10 @@ const aiChat = getAiChatManager() // The session workspace's config in a session pane, so new loops match the IteratorGen shown. const aiOff = $derived(disableAi || !aiChat.aiInfo?.enabled) + // A step's description goes to the session's chat or to a new session: with neither, it + // would be dropped. + const inSession = !!getContext('aiChatManager') + const stepGenOff = $derived(disableAi || (!inSession && !sessionOpen)) const { customUi, selectionManager, history, flowStateStore, flowStore, pathStore, opWorkspace } = getContext<FlowEditorContext>('FlowEditorContext') @@ -494,7 +498,7 @@ > <FlowStickyNode compact={compactTopbar} - {disableAi} + disableAi={stepGenOff} {showFlowAiButton} {disableSettings} {disableStaticInputs} @@ -515,7 +519,7 @@ triggerNode={customUi?.triggers != false} path={$pathStore} {newFlow} - {disableAi} + disableAi={stepGenOff} insertable scroll {minHeight} diff --git a/frontend/src/lib/components/flows/map/MapItem.svelte b/frontend/src/lib/components/flows/map/MapItem.svelte index e957665a6b..98bf84176f 100644 --- a/frontend/src/lib/components/flows/map/MapItem.svelte +++ b/frontend/src/lib/components/flows/map/MapItem.svelte @@ -32,6 +32,8 @@ nodeState?: FlowNodeState duration_ms?: number | undefined retries?: number | undefined + /** In a run, while its concurrency limit holds the step back. */ + held?: { since?: string; nextCheck?: Date | string } flowJobs: | { flowJobs: string[] @@ -83,6 +85,7 @@ nodeState, duration_ms = undefined, retries = undefined, + held = undefined, flowJobs, attempts = undefined, editMode = false, @@ -213,7 +216,13 @@ label={`${ mod.summary || (mod.value.type == 'forloopflow' ? 'For loop' : 'While loop') } ${mod.value.parallel ? '(parallel)' : ''} ${ - mod.value.skip_failures ? '(skip failures)' : '' + mod.value.skip_failures + ? mod.value.failure_threshold?.type === 'static' + ? `(skip failures, stop at ${mod.value.failure_threshold.value})` + : mod.value.failure_threshold + ? '(skip failures, failure threshold)' + : '(skip failures)' + : '' } ${mod.value.squash ? '(squash)' : ''}`} id={mod.id} on:changeId @@ -283,6 +292,7 @@ {:else} <FlowModuleSchemaItem {retries} + {held} attempts={attempts && !insertable ? { jobs: attempts.flowJobs, diff --git a/frontend/src/lib/components/flows/map/StepSettingsBar.svelte b/frontend/src/lib/components/flows/map/StepSettingsBar.svelte index d2b035d561..1cc216fe80 100644 --- a/frontend/src/lib/components/flows/map/StepSettingsBar.svelte +++ b/frontend/src/lib/components/flows/map/StepSettingsBar.svelte @@ -15,7 +15,7 @@ import DropdownV2 from '$lib/components/DropdownV2.svelte' import { Button } from '$lib/components/common' import { fade } from 'svelte/transition' - import type { Item } from '$lib/utils' + import { msToCompactDuration, type Item } from '$lib/utils' import AttemptPicker from './AttemptPicker.svelte' import type { StepSettingKey, StepSettingView } from '../flowStepSettings' @@ -25,6 +25,8 @@ /** Failed attempts so far. */ retries?: number attempts?: RetryAttempts + /** In a run, while its concurrency limit holds the step back. */ + held?: { since?: string; nextCheck?: Date | string } /** Makes each setting's row open that setting in the step's settings panel. */ onOpenSetting?: (key: StepSettingKey) => void onOpenChange?: (open: boolean) => void @@ -34,6 +36,7 @@ settings, retries = undefined, attempts = undefined, + held = undefined, onOpenSetting, onOpenChange }: Props = $props() @@ -87,9 +90,26 @@ // With nothing else to list, the menu is the attempt list itself, one hover fewer. let attemptsOnly = $derived(!!pickerProps && settings.length === 1) + // Read as the menu opens: the held time it shows does not tick. + let heldDetail = $derived( + held?.since && open + ? ` · held ${msToCompactDuration(Math.max(Date.now() - new Date(held.since).getTime(), 0), 0)}` + : held + ? ' · held' + : undefined + ) + let items: Item[] = $derived( ordered.map((s) => { const action = onOpenSetting && (() => onOpenSetting(s.key)) + if (s.key === 'concurrency' && heldDetail) + return { + displayName: s.label, + icon: s.icon, + iconColor: '#f97316', + detail: s.summary.text + heldDetail, + action + } if (s.key !== 'retries') return { displayName: s.label, icon: s.icon, detail: s.summary.text, action } if (pickerProps) { @@ -143,13 +163,14 @@ unifiedSize="2xs" wrapperClasses="bg-surface rounded-md" btnClasses="px-2" - title="Step settings" + title={held ? 'Step settings: held by its concurrency limit' : 'Step settings'} > <span class="flex flex-row items-center gap-1.5"> {#each shown as s (s.key)} {@const Icon = s.icon} <span - class="flex flex-row items-center gap-0.5 {s.key === 'retries' && retries + class="flex flex-row items-center gap-0.5 {(s.key === 'retries' && retries) || + (s.key === 'concurrency' && held) ? 'text-orange-500' : ''}" > diff --git a/frontend/src/lib/components/graph/approvalCount.svelte.ts b/frontend/src/lib/components/graph/approvalCount.svelte.ts new file mode 100644 index 0000000000..1600bbc1e5 --- /dev/null +++ b/frontend/src/lib/components/graph/approvalCount.svelte.ts @@ -0,0 +1,28 @@ +import { JobService } from '$lib/gen' +import type { GraphModuleState } from './model' + +/** How many approvals a waiting step has received so far. Approvals coming in do not change the + * run until the last one, so the count is read on its own, and only when there is more than one + * to count. */ +export function useApprovalCount(wait: () => GraphModuleState['approval_wait']) { + let count = $state<number | undefined>(undefined) + $effect(() => { + const w = wait() + if (!w || w.required <= 1 || !w.workspace) return + const args = { workspace: w.workspace, jobId: w.job, stepId: w.step } + const read = () => + JobService.getApprovalStepDetail(args) + .then((d) => (count = d.approvals.length)) + .catch(() => {}) + read() + const id = setInterval(read, 10000) + return () => clearInterval(id) + }) + return { + /** "Waiting for approval", with "· 1 of 2" once some are in. */ + get label() { + const w = wait() + return `Waiting for approval${count && w ? ` · ${count} of ${w.required}` : ''}` + } + } +} diff --git a/frontend/src/lib/components/graph/flowRunStatus.svelte.ts b/frontend/src/lib/components/graph/flowRunStatus.svelte.ts index 39886c5737..8233713c2b 100644 --- a/frontend/src/lib/components/graph/flowRunStatus.svelte.ts +++ b/frontend/src/lib/components/graph/flowRunStatus.svelte.ts @@ -44,6 +44,20 @@ export class FlowRunStatus { return count } + /** Steps inside the subflow step `id`, at any depth, waiting for an approval, waiting out a + * sleep or held by their concurrency limit. */ + waitingStepsInside(id: string): { approval: number; sleep: number; concurrency: number } { + const prefix = (id.startsWith('subflow:') ? id : 'subflow:' + id) + ':' + const count = { approval: 0, sleep: 0, concurrency: 0 } + for (const [key, state] of this.#moduleStates) { + if (!key.startsWith(prefix)) continue + if (state.approval_wait) count.approval++ + else if (state.type === 'WaitingForExecutor' && state.waiting_reason) + count[state.waiting_reason]++ + } + return count + } + setModuleStates(next: Record<string, GraphModuleState> | undefined) { const incoming = next ?? {} for (const id of [...this.#moduleStates.keys()]) { diff --git a/frontend/src/lib/components/graph/model.ts b/frontend/src/lib/components/graph/model.ts index fde7b7799a..1468973644 100644 --- a/frontend/src/lib/components/graph/model.ts +++ b/frontend/src/lib/components/graph/model.ts @@ -29,8 +29,8 @@ export type DurationStatus = { export type FlowStatusViewerContext = { flowState?: FlowState - retryStatus: StateStore<Record<string, number | undefined>> - suspendStatus: StateStore<Record<string, { nb: number; job: Job }>> + /** `prefix`: the subflow step ids leading to the run, as `buildPrefix` chains them. */ + suspendStatus: StateStore<Record<string, { nb: number; job: Job; prefix?: string }>> hideDownloadInGraph?: boolean hideTimeline?: boolean hideNodeDefinition?: boolean @@ -47,6 +47,15 @@ export type GraphModuleState = { result?: any tag?: string scheduled_for?: Date + /** Why a `WaitingForExecutor` step is due later: the previous step's sleep, or its own + * concurrency limit holding it back (`concurrency_key`). */ + waiting_reason?: 'sleep' | 'concurrency' + /** On the step waiting for the approval step `step` before it: their run, and how many + * approvals it needs. */ + approval_wait?: { job: string; workspace?: string; step: string; required: number } + /** When its concurrency limit first held the step back. */ + held_since?: string + concurrency_key?: string job_id?: string parent_module?: string selectedForloop?: string diff --git a/frontend/src/lib/components/graph/renderers/nodes/ModuleNode.svelte b/frontend/src/lib/components/graph/renderers/nodes/ModuleNode.svelte index 2e2539fa8d..34db0d4e02 100644 --- a/frontend/src/lib/components/graph/renderers/nodes/ModuleNode.svelte +++ b/frontend/src/lib/components/graph/renderers/nodes/ModuleNode.svelte @@ -8,10 +8,14 @@ StickyNote, PictureInPicture2, Bug, - RefreshCw + RefreshCw, + Gauge, + Hourglass, + Moon } from 'lucide-svelte' import DropdownV2 from '$lib/components/DropdownV2.svelte' import NodeWrapper from './NodeWrapper.svelte' + import WaitingMark from './WaitingMark.svelte' import AiDecisionNodeBranch from './AiDecisionNodeBranch.svelte' import type { ModuleN } from '../../graphBuilder.svelte' import { jobToGraphModuleState } from '$lib/components/modulesTest.svelte' @@ -219,6 +223,24 @@ : undefined }) + // Live, so it takes the slot of the retried and error handler counts while it lasts. + let waitingInside = $derived.by(() => { + if (!flowRunStatus?.showsRun || data.editMode || data.module?.value?.type !== 'flow') return + const { approval, sleep, concurrency } = flowRunStatus.waitingStepsInside(data.id) + if (approval > 0) + return { + reason: 'approval' as const, + label: `${approval === 1 ? 'Approval' : `${approval} approvals`} waiting inside` + } + if (concurrency > 0) + return { + reason: 'concurrency' as const, + label: `${concurrency} step${concurrency === 1 ? '' : 's'} held by concurrency limit` + } + if (sleep > 0) + return { reason: 'sleep' as const, label: `${sleep} step${sleep === 1 ? '' : 's'} sleeping` } + }) + let type = $derived.by(() => { let typ = state?.type if (!typ && flowJobs) { @@ -319,6 +341,9 @@ nodeState={state?.skipped ? '_Skipped' : type} duration_ms={state?.duration_ms} retries={state?.retries} + held={type === 'WaitingForExecutor' && state?.waiting_reason === 'concurrency' + ? { since: state.held_since, nextCheck: state.scheduled_for } + : undefined} {flowJobs} {attempts} on:delete={(e) => { @@ -352,11 +377,61 @@ : undefined} /> - {#await hiddenErrorHandlers} - {@render insideBar(retriedInside, undefined)} - {:then handlers} - {@render insideBar(retriedInside, handlers)} - {/await} + {#if type === 'WaitingForExecutor' && state?.waiting_reason} + <WaitingMark + reason={state.waiting_reason} + until={state.scheduled_for} + concurrencyKey={state.concurrency_key} + heldSince={state.held_since} + onclick={() => data.module && data.eventHandlers.select(data.module.id)} + /> + {:else if state?.approval_wait} + <WaitingMark + reason="approval" + approvalWait={state.approval_wait} + onclick={() => data.module && data.eventHandlers.select(data.module.id)} + /> + {/if} + {#if waitingInside} + <!-- svelte-ignore a11y_no_static_element_interactions --> + <div + class="nodrag nopan absolute -left-1 top-[calc(100%+3px)] z-10" + onpointerdown={(e) => e.stopPropagation()} + > + <Button + variant="subtle" + unifiedSize="2xs" + startIcon={{ + icon: + waitingInside.reason === 'approval' + ? Hourglass + : waitingInside.reason === 'sleep' + ? Moon + : Gauge, + classes: + waitingInside.reason === 'approval' + ? 'text-violet-500' + : waitingInside.reason === 'sleep' + ? '' + : 'text-orange-500' + }} + btnClasses="text-2xs text-secondary gap-1" + title="Expand to see the waiting steps" + onClick={(e) => { + e?.stopPropagation() + expandSubflow() + }} + > + {waitingInside.label} + </Button> + </div> + {:else} + {#await hiddenErrorHandlers} + {@render insideBar(retriedInside, undefined)} + {:then handlers} + {@render insideBar(retriedInside, handlers)} + {/await} + {/if} {#if (data.module?.value?.type === 'branchall' || data.module?.value?.type === 'branchone') && data.insertable} <div class="absolute -bottom-10 left-1/2 transform -translate-x-1/2 z-10 flex gap-1"> diff --git a/frontend/src/lib/components/graph/renderers/nodes/WaitingMark.svelte b/frontend/src/lib/components/graph/renderers/nodes/WaitingMark.svelte new file mode 100644 index 0000000000..871505e92a --- /dev/null +++ b/frontend/src/lib/components/graph/renderers/nodes/WaitingMark.svelte @@ -0,0 +1,79 @@ +<script lang="ts"> + import { Gauge, Hourglass, Moon } from 'lucide-svelte' + import { Button } from '$lib/components/common' + import { useApprovalCount } from '../../approvalCount.svelte' + import { displayDate, msToCompactDuration } from '$lib/utils' + import type { GraphModuleState } from '../../model' + + type Props = { onclick: () => void } & ( + | { + reason: NonNullable<GraphModuleState['waiting_reason']> + until: Date | string | undefined + concurrencyKey?: string + heldSince?: string + } + | { + reason: 'approval' + approvalWait: NonNullable<GraphModuleState['approval_wait']> + } + ) + + let props: Props = $props() + + let now = $state(Date.now()) + $effect(() => { + if (props.reason === 'approval') return + const id = setInterval(() => (now = Date.now()), 1000) + return () => clearInterval(id) + }) + + const approval = useApprovalCount(() => + props.reason === 'approval' ? props.approvalWait : undefined + ) + + let label = $derived.by(() => { + if (props.reason === 'approval') return approval.label + if (props.reason === 'sleep') + return `Sleeping · ${msToCompactDuration(Math.max(new Date(props.until ?? now).getTime() - now, 0), 0)}` + const held = props.heldSince + ? msToCompactDuration(Math.max(now - new Date(props.heldSince).getTime(), 0), 0) + : undefined + return `Held by concurrency limit${held ? ` · ${held}` : ''}` + }) + let title = $derived.by(() => { + if (props.reason === 'approval') return 'The run waits for this step to be approved' + if (props.reason === 'sleep') + return `Sleeping after the previous step until ${displayDate(props.until, true)}` + return `Held by its concurrency limit${props.concurrencyKey ? ` (key ${props.concurrencyKey})` : ''}, next check by ${displayDate(props.until, true)}` + }) +</script> + +<!-- What keeps a step from starting sits above it; finished steps show how long they ran at the + other end of that edge. --> +<!-- svelte-ignore a11y_no_static_element_interactions --> +<div + class="nodrag nopan absolute -left-1 bottom-[calc(100%+3px)] z-10" + onpointerdown={(e) => e.stopPropagation()} +> + <Button + variant="subtle" + unifiedSize="2xs" + startIcon={{ + icon: props.reason === 'approval' ? Hourglass : props.reason === 'sleep' ? Moon : Gauge, + classes: + props.reason === 'approval' + ? 'text-violet-500' + : props.reason === 'concurrency' + ? 'text-orange-500' + : '' + }} + btnClasses="text-2xs text-secondary gap-1" + {title} + onClick={(e) => { + e?.stopPropagation() + props.onclick() + }} + > + {label} + </Button> +</div> diff --git a/frontend/src/lib/components/home/RecentRunRow.svelte b/frontend/src/lib/components/home/RecentRunRow.svelte index fb67421933..14865e6819 100644 --- a/frontend/src/lib/components/home/RecentRunRow.svelte +++ b/frontend/src/lib/components/home/RecentRunRow.svelte @@ -1,8 +1,9 @@ <script lang="ts"> import { goto } from '$app/navigation' import { workspaceStore } from '$lib/stores' - import { CircleCheck, CircleSlash, CircleX, EyeOff, Loader2, Wrench } from 'lucide-svelte' + import { CircleCheck, CircleSlash, CircleX, EyeOff, Hourglass, Wrench } from 'lucide-svelte' import { Button } from '$lib/components/common' + import RunningStatusIcon from '$lib/components/runs/RunningStatusIcon.svelte' import DropdownV2 from '$lib/components/DropdownV2.svelte' import { useRoleCapabilities } from '$lib/operatorWriteRights' import { @@ -55,14 +56,18 @@ failure: 'Failed', resolved: 'Failed, resolved', canceled: 'Canceled', - running: 'Running' + running: 'Running', + suspended: 'Awaiting approval' } + // Waiting for a person is neither progress nor trouble: violet, as a suspended job is + // everywhere else, not running's yellow. const barClass = { success: 'bg-green-500 dark:bg-green-600', failure: 'bg-red-500 dark:bg-red-600', resolved: 'bg-orange-300 dark:bg-orange-700', canceled: 'bg-gray-400 dark:bg-gray-500', - running: 'bg-yellow-500' + running: 'bg-yellow-500', + suspended: 'bg-violet-400 dark:bg-violet-500' } function runTooltip(run: RecentRun) { @@ -102,7 +107,9 @@ > <span class="flex w-3.5 shrink-0 justify-center"> {#if item.status === 'running'} - <Loader2 size={14} class="animate-spin text-yellow-500" /> + <span class="flex text-yellow-500" title="Running"><RunningStatusIcon /></span> + {:else if item.status === 'suspended'} + <span class="text-violet-500" title="Awaiting approval"><Hourglass size={14} /></span> {:else if failing} <CircleX size={14} class="text-red-500" /> {:else if item.status === 'resolved'} @@ -219,6 +226,8 @@ {#if latest} <a href={runHref(latest.id, $workspaceStore)} + target="_blank" + rel="noopener" class="absolute inset-0 text-right font-medium text-accent opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 hover:underline" aria-label="Open the latest run of {title}" onclick={(e) => e.stopPropagation()} diff --git a/frontend/src/lib/components/home/WaitingApprovalsHeaderStatus.svelte b/frontend/src/lib/components/home/WaitingApprovalsHeaderStatus.svelte new file mode 100644 index 0000000000..bf2cfaeba3 --- /dev/null +++ b/frontend/src/lib/components/home/WaitingApprovalsHeaderStatus.svelte @@ -0,0 +1,68 @@ +<script lang="ts"> + import Popover from '$lib/components/meltComponents/Popover.svelte' + import { Button } from '$lib/components/common' + import { ChevronDown, Hourglass, PanelRightOpen } from 'lucide-svelte' + import WaitingApprovalsList from './WaitingApprovalsList.svelte' + import type { WaitingApprovalsState } from './waitingApprovals.svelte' + + interface Props { + approvals: WaitingApprovalsState + /** Absent below the width the side column needs: there is no section to add. */ + onShowSection?: () => void + /** A narrow bar: the hourglass and the count. */ + compact?: boolean + } + + let { approvals, onShowSection, compact = false }: Props = $props() + + let isOpen = $state(false) + let label = $derived( + `${approvals.total} run${approvals.total === 1 ? '' : 's'} waiting for your approval` + ) +</script> + +<!-- Shaped like the recent-runs status beside it: both are statuses of the workspace's runs, where + the buttons before them are its changes. --> +<div class="flex items-center h-[22px] pl-2.5 ml-1.5 border-l border-border-light wm-page-in"> + <Popover + openOnHover + debounceDelay={140} + placement="bottom-end" + bind:isOpen + triggerAttrs={{ 'aria-label': label }} + class="flex items-center gap-1.5 h-7 pl-2 pr-1.5 -mr-1.5 rounded-md text-xs font-normal text-violet-600 dark:text-violet-400 whitespace-nowrap tabular-nums hover:bg-surface-secondary {isOpen + ? 'bg-surface-secondary' + : ''}" + > + {#snippet trigger()} + <Hourglass size={14} /> + {approvals.total}{compact ? '' : ' to approve'} + {#if !compact} + <ChevronDown size={12} class="text-hint" /> + {/if} + {/snippet} + {#snippet content()} + <div class="w-[380px] max-w-[calc(100vw-32px)] p-1.5 text-xs"> + <div class="px-2.5 pt-2 pb-1.5"> + <b class="font-semibold text-emphasis text-[12.5px]">Awaiting your approval</b> + </div> + <WaitingApprovalsList {approvals} class="max-h-[352px]" onOpen={() => (isOpen = false)} /> + {#if onShowSection} + <div class="flex justify-end mt-1.5 pt-2 px-1.5 pb-1 border-t border-border-light"> + <Button + variant="subtle" + unifiedSize="sm" + startIcon={{ icon: PanelRightOpen }} + onclick={() => { + isOpen = false + onShowSection() + }} + > + Show approvals on home + </Button> + </div> + {/if} + </div> + {/snippet} + </Popover> +</div> diff --git a/frontend/src/lib/components/home/WaitingApprovalsList.svelte b/frontend/src/lib/components/home/WaitingApprovalsList.svelte new file mode 100644 index 0000000000..279af5cda4 --- /dev/null +++ b/frontend/src/lib/components/home/WaitingApprovalsList.svelte @@ -0,0 +1,51 @@ +<script lang="ts"> + import { Hourglass } from 'lucide-svelte' + import { workspaceStore } from '$lib/stores' + import { + approvalAge, + approvalDetail, + approvalHref, + approvalTitle, + type WaitingApprovalsState + } from './waitingApprovals.svelte' + + interface Props { + approvals: WaitingApprovalsState + /** Caps the list's height; it scrolls inside it, so a long queue never pushes past it. */ + class?: string + onOpen?: () => void + } + + let { approvals, class: classNames = '', onOpen }: Props = $props() + + let hidden = $derived(approvals.total - approvals.approvals.length) +</script> + +<div class="overflow-y-auto overscroll-contain scrollbar-subtle {classNames}"> + {#each approvals.approvals as a (a.job_id)} + <a + href={approvalHref(a, $workspaceStore)} + target="_blank" + rel="noopener" + onclick={onOpen} + class="flex items-center gap-2.5 min-h-[42px] px-2.5 py-[5px] rounded-md hover:bg-surface-hover focus-visible:bg-surface-hover outline-none" + > + <span class="flex w-3.5 shrink-0 justify-center text-violet-500"> + <Hourglass size={14} /> + </span> + <span class="flex flex-col min-w-0 flex-1"> + <span class="truncate text-[12.5px] font-medium text-primary">{approvalTitle(a)}</span> + <span class="truncate text-[10.5px] text-hint">{approvalDetail(a)}</span> + </span> + <span class="w-[46px] shrink-0 text-right text-[11px] text-hint"> + {approvalAge(a, approvals.now)} + </span> + </a> + {/each} +</div> +{#if hidden > 0} + <!-- The server lists the most recent only: say what is left out rather than end as if complete. --> + <p class="px-2.5 pt-1 text-[11.5px] text-hint"> + {hidden} older run{hidden === 1 ? '' : 's'} also waiting + </p> +{/if} diff --git a/frontend/src/lib/components/home/WaitingApprovalsPanel.svelte b/frontend/src/lib/components/home/WaitingApprovalsPanel.svelte new file mode 100644 index 0000000000..473207ba8a --- /dev/null +++ b/frontend/src/lib/components/home/WaitingApprovalsPanel.svelte @@ -0,0 +1,32 @@ +<script lang="ts"> + import { Button } from '$lib/components/common' + import { PanelRightClose } from 'lucide-svelte' + import WaitingApprovalsList from './WaitingApprovalsList.svelte' + import type { WaitingApprovalsState } from './waitingApprovals.svelte' + + interface Props { + approvals: WaitingApprovalsState + onCollapse: () => void + } + + let { approvals, onCollapse }: Props = $props() +</script> + +<div class="flex flex-col min-h-0 h-full"> + <div class="flex items-center gap-2 shrink-0 pb-2"> + <h2 class="flex items-baseline gap-1.5 min-w-0 flex-1 text-[13px] font-medium text-primary"> + <span class="whitespace-nowrap">Awaiting your approval</span> + <span class="text-xs font-normal text-hint tabular-nums">{approvals.total}</span> + </h2> + <Button + variant="subtle" + unifiedSize="sm" + iconOnly + startIcon={{ icon: PanelRightClose }} + onclick={onCollapse} + aria-label="Hide approvals" + title="Hide approvals" + /> + </div> + <WaitingApprovalsList {approvals} class="flex-1 min-h-0 -mx-2.5" /> +</div> diff --git a/frontend/src/lib/components/home/recentRuns.svelte.ts b/frontend/src/lib/components/home/recentRuns.svelte.ts index 63fc73bb8d..ace856522e 100644 --- a/frontend/src/lib/components/home/recentRuns.svelte.ts +++ b/frontend/src/lib/components/home/recentRuns.svelte.ts @@ -128,10 +128,9 @@ export function useRecentRuns( export type RecentRunsState = ReturnType<typeof useRecentRuns> -const PANEL_OPEN_SETTING = 'wm-home-runs-open' - -export function usePanelOpen() { - let open = $state(getLocalSetting(PANEL_OPEN_SETTING) !== 'false') +/** Whether a Home side-column section is shown; on until the user hides it. */ +export function usePanelOpen(setting: string = 'wm-home-runs-open') { + let open = $state(getLocalSetting(setting) !== 'false') return { get val() { return open @@ -139,7 +138,7 @@ export function usePanelOpen() { set val(v: boolean) { open = v try { - storeLocalSetting(PANEL_OPEN_SETTING, v ? undefined : 'false') + storeLocalSetting(setting, v ? undefined : 'false') } catch {} } } @@ -176,7 +175,7 @@ export function windowLabel(hours: number) { return hours > 24 && hours % 24 === 0 ? `last ${hours / 24}d` : `last ${hours}h` } -/** `now`, `3m`, `2h`, `4d`; `running` while the newest run has not finished. */ +/** `now`, `3m`, `2h`, `4d` since the newest run started; `running` while it is running. */ export function shortAge(run: RecentRun, now: number) { if (run.status === 'running') return 'running' const s = Math.max(0, (now - new Date(run.ran_at).getTime()) / 1000) diff --git a/frontend/src/lib/components/home/waitingApprovals.svelte.ts b/frontend/src/lib/components/home/waitingApprovals.svelte.ts new file mode 100644 index 0000000000..c77d9ecae6 --- /dev/null +++ b/frontend/src/lib/components/home/waitingApprovals.svelte.ts @@ -0,0 +1,76 @@ +import { JobService, type ListWaitingApprovalsResponse } from '$lib/gen' +import { IsDocumentVisible, useInterval } from 'runed' +import { persistedResource } from '$lib/persistedResource.svelte' + +export type WaitingApproval = ListWaitingApprovalsResponse['approvals'][number] + +/** An approval waits on a person, who acts within minutes, not seconds; Home stays open in many + * tabs. */ +const REFRESH_MS = 60000 + +/** + * The runs waiting for an approval the user can give, read from `listWaitingApprovals`. The + * header status and the side section read the same instance, so their counts agree. + */ +export function useWaitingApprovals(workspace: () => string | undefined) { + const res = persistedResource( + () => ({ workspace: workspace() }), + async ({ workspace }) => + workspace ? await JobService.listWaitingApprovals({ workspace }) : undefined, + { + name: 'waiting_approvals', + version: 1, + scope: ({ workspace }) => (workspace ? { workspace, args: {} } : undefined) + } + ) + let now = $state(Date.now()) + const visible = new IsDocumentVisible() + useInterval(REFRESH_MS, { + callback: () => { + if (!visible.current) return + now = Date.now() + if (!res.loading) res.refetch() + } + }) + return { + get approvals(): WaitingApproval[] { + return res.current?.approvals ?? [] + }, + /** All the runs waiting, of which `approvals` holds the most recent. */ + get total(): number { + return res.current?.total ?? 0 + }, + get now() { + return now + } + } +} + +export type WaitingApprovalsState = ReturnType<typeof useWaitingApprovals> + +/** The approval page, which shows an approver that one run even without read access to it. */ +export function approvalHref(a: WaitingApproval, workspace: string | undefined) { + return `/approve/${workspace ?? ''}/${a.job_id}` +} + +export function approvalTitle(a: WaitingApproval) { + return a.flow_summary || a.flow_path?.split('/').pop() || 'Flow' +} + +export function approvalDetail(a: WaitingApproval) { + return [ + a.step_summary, + `started by ${a.started_by}`, + a.required_approvals > 1 ? `${a.approvals} of ${a.required_approvals} approvals` : undefined + ] + .filter(Boolean) + .join(' · ') +} + +export function approvalAge(a: WaitingApproval, now: number) { + const s = Math.max(0, (now - new Date(a.created_at).getTime()) / 1000) + if (s < 60) return 'now' + if (s < 3600) return `${Math.floor(s / 60)}m` + if (s < 86400) return `${Math.floor(s / 3600)}h` + return `${Math.floor(s / 86400)}d` +} diff --git a/frontend/src/lib/components/instanceSettings.ts b/frontend/src/lib/components/instanceSettings.ts index bd909e5711..4a647d7103 100644 --- a/frontend/src/lib/components/instanceSettings.ts +++ b/frontend/src/lib/components/instanceSettings.ts @@ -8,6 +8,7 @@ import { parseCount } from '$lib/parseCount' import { writable } from 'svelte/store' import { OidcService } from '$lib/gen' import { workspaceRolesErrors } from '$lib/workspaceRoles' +import { clientIpHeaderError, trustedProxiesErrors } from '$lib/clientIpTrust' import { deepEqual } from 'fast-equals' /** @@ -84,7 +85,10 @@ export interface Setting { | 'accent_color' | 'agent_workload_identity_issuers' | 'mcp_external_idp' + | 'instance_ip_allowlist' | 'workspace_roles' + /** Drawn by the Client IP page itself, beside what the server reports it trusts. */ + | 'client_ip' storage: SettingStorage advancedToggle?: { label: string @@ -871,6 +875,17 @@ export const settings: Record<string, Setting[]> = { fieldType: 'boolean', storage: 'setting' }, + { + label: 'Require two-factor authentication', + description: + 'Password logins ask for a code from an authenticator app. Users without two-factor authentication set it up at their next login.', + tooltip: + 'Users cannot turn it off while this is on. OAuth and SAML logins are not affected: enforce two-factor authentication at the identity provider. Sessions that already exist are no longer renewed for users without it, so they end within 3 days by default.', + key: 'require_totp', + fieldType: 'boolean', + storage: 'setting', + ee_only: '' + }, { label: 'Auto-login SSO provider', description: 'Send the login page straight to this provider.', @@ -944,6 +959,38 @@ export const settings: Record<string, Setting[]> = { ], 'DB Health': [], 'OIDC signing': [], + 'Client IP': [ + { + label: 'Trusted proxies', + key: 'trusted_proxies', + fieldType: 'client_ip', + storage: 'setting', + isValid: (v: unknown) => trustedProxiesErrors(v).length === 0 + }, + { + label: 'Trust Cloudflare', + key: 'trust_cloudflare', + fieldType: 'client_ip', + storage: 'setting' + }, + { + label: 'Client IP header', + key: 'client_ip_header', + fieldType: 'client_ip', + storage: 'setting', + isValid: (v: unknown) => clientIpHeaderError(v) === undefined + }, + { + label: 'IP allowlist', + description: + 'Refuse every API request whose client address is not listed, before it is authenticated.', + key: 'instance_ip_allowlist', + fieldType: 'instance_ip_allowlist', + storage: 'setting', + ee_only: '', + hideInQuickSetup: true + } + ], Registries: [ { label: 'Instance Python Version', @@ -1123,6 +1170,16 @@ export const settings: Record<string, Setting[]> = { storage: 'setting', ee_only: '' }, + { + label: 'CRAN repository URL', + description: + 'CRAN mirror R scripts resolve and install packages from, instead of https://cloud.r-project.org (e.g. a Nexus or Posit Package Manager proxy). Also settable with the <code>CRAN_REPO_URL</code> environment variable', + key: 'cran_repo_url', + fieldType: 'password', + placeholder: 'https://user:password@nexus.foo.com/repository/cran/', + storage: 'setting', + ee_only: '' + }, { label: 'Cargo registries', description: 'Write a .cargo/config.toml to set custom Cargo registries and credentials', @@ -1465,6 +1522,13 @@ export const instanceSettingsNavigationGroups = [ aiDescription: 'Instance SCIM/SAML settings', isEE: true }, + { + id: 'client_ip', + label: 'Client IP', + aiId: 'instance-settings-client-ip', + aiDescription: + 'Which proxies are trusted to report the client address recorded in audit logs and used by login rate limits and token IP allowlists' + }, { id: 'agent_workers', label: 'Agent workers', @@ -1637,6 +1701,7 @@ export const tabToCategoryMap: Record<string, string> = { websocket: 'WebSocket', db_health: 'DB Health', oidc_signing: 'OIDC signing', + client_ip: 'Client IP', agent_workers: 'Agent workers', lsp: 'LSP' } @@ -1701,6 +1766,7 @@ export const categoryToTabMap: Record<string, string> = { WebSocket: 'websocket', 'DB Health': 'db_health', 'OIDC signing': 'oidc_signing', + 'Client IP': 'client_ip', 'Agent workers': 'agent_workers', LSP: 'lsp' } diff --git a/frontend/src/lib/components/instanceSettings/ClientIpStatus.svelte b/frontend/src/lib/components/instanceSettings/ClientIpStatus.svelte new file mode 100644 index 0000000000..0052a14f34 --- /dev/null +++ b/frontend/src/lib/components/instanceSettings/ClientIpStatus.svelte @@ -0,0 +1,313 @@ +<script lang="ts"> + import { SettingService, type ClientIpDiagnostics, type ClientIpTrustView } from '$lib/gen' + import { Alert, Badge, Skeleton } from '$lib/components/common' + import DataTable from '$lib/components/table/DataTable.svelte' + import Head from '$lib/components/table/Head.svelte' + import Cell from '$lib/components/table/Cell.svelte' + import TextInput from '$lib/components/text_input/TextInput.svelte' + import Toggle from '$lib/components/Toggle.svelte' + import { displayDate } from '$lib/utils' + import { resource } from 'runed' + import { enterpriseLicense } from '$lib/stores' + import { instanceSettingsSaved } from '$lib/components/instanceSettings' + import { appendTrustedProxy, clientIpHeaderError, trustedProxiesErrors } from '$lib/clientIpTrust' + import type { Writable } from 'svelte/store' + + interface Props { + values: Writable<Record<string, any>> + loading: boolean + } + + let { values, loading }: Props = $props() + + // Refetched after a save: the server answering applies a change before it responds. + const diagnostics = resource( + () => $instanceSettingsSaved, + (): Promise<ClientIpDiagnostics> => SettingService.getClientIpDiagnostics() + ) + let status = $derived(diagnostics.current) + let configuration = $derived(status?.configuration) + let loadError = $derived.by(() => { + const e: any = diagnostics.error + return e ? (e.body ?? e.message ?? String(e)) : undefined + }) + + // The proxy this very request came through, to name in TRUSTED_PROXIES: only a private one, + // since a public one trusted for attribution is a Cloudflare edge no allowlist may trust. + const PRIVATE_V4 = /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/ + function isPrivate(ip: string): boolean { + return PRIVATE_V4.test(ip) || /^f[cd][0-9a-f]{2}:/i.test(ip) + } + let ownProxy = $derived( + status?.peer && + status.forwarding_header != undefined && + status.client_ip !== status.peer && + isPrivate(status.peer) + ? status.peer + : undefined + ) + let ownRequestUntrusted = $derived( + status?.forwarding_header != undefined && status.client_ip === status.peer + ) + + let trustedProxiesFromEnv = $derived(configuration?.trusted_proxies.from_env ?? false) + let proxiesErrors = $derived(trustedProxiesErrors($values?.trusted_proxies)) + let headerError = $derived(clientIpHeaderError($values?.client_ip_header)) + + /** The address to offer under "Trust this proxy", unless saving it would be refused. */ + function trustable(ip: string | undefined): string | undefined { + if (!ip || trustedProxiesFromEnv || trustedProxiesErrors(ip).length > 0) return undefined + return ip + } + /** `keepDefault`: add the proxy to the private ranges trusted by default, rather than narrow + * the trust to it alone, which is what the warning about that default asks for. */ + function trustAction(ip: string | undefined, keepDefault: boolean) { + const t = trustable(ip) + if (!t) return [] + return [ + { + label: `Trust ${t}`, + variant: 'default' as const, + onClick: () => { + $values.trusted_proxies = appendTrustedProxy($values.trusted_proxies, t, keepDefault) + } + } + ] + } + + function describe(view: ClientIpTrustView): string { + const parts = [...view.networks] + for (const h of view.hosts) { + parts.push( + h.addresses.length ? `${h.name} (${h.addresses.join(', ')})` : `${h.name} (unresolved)` + ) + } + if (view.cloudflare) parts.push('Cloudflare') + return parts.length ? parts.join(', ') : 'no proxy' + } +</script> + +{#snippet fromEnv(variable: string, value: string, stored: unknown)} + <div class="text-xs text-primary"> + {#if value}<code>{value}</code>{:else}<span class="text-secondary">empty</span>{/if} + <div class="text-2xs text-secondary mt-1"> + Set by the <code>{variable}</code> environment variable of the server{#if variable === 'TRUSTED_PROXIES'}{' '}(Helm: + <code>windmill.trustedProxies</code>){/if}, which takes precedence. Unset it to edit it + here. + {#if stored !== undefined && stored !== null && stored !== ''} + A value is also saved here (<code>{typeof stored === 'boolean' + ? stored + ? 'on' + : 'off' + : String(stored)}</code>); it applies once the variable is unset. + {/if} + </div> + </div> +{/snippet} + +{#if loadError} + <Alert type="error" title="Could not load the client IP status">{loadError}</Alert> +{:else if status && configuration} + <div class="flex flex-col gap-6"> + {#if !$enterpriseLicense} + <Alert type="info" title="Mostly used by Enterprise features"> + Audit logs and token IP allowlists, which record and check the client IP, are Enterprise + features. On this edition it only keys the per-IP login rate limit, when + <code>LOGIN_RATE_LIMIT_PER_IP</code> is set. + </Alert> + {/if} + {#if ownRequestUntrusted} + <Alert + type="warning" + title="Your own request came through a proxy Windmill does not trust" + actions={trustAction(status.peer ?? undefined, true)} + > + It arrived from <code>{status.peer}</code> with the forwarding header + <code>{status.forwarding_header}</code>, so Windmill records <code>{status.peer}</code> as the + client of every request through it. Add that address (or its network) to the trusted proxies + below, or turn on Trust Cloudflare if it is Cloudflare. + </Alert> + {/if} + + {#if status.private_ranges_trusted} + <Alert + type="warning" + title="Any host on your private network is trusted as a proxy" + actions={trustAction(ownProxy, false)} + > + {status.trusted_proxies_set + ? 'The trusted proxies include a whole private range' + : 'No trusted proxies are configured'}, so Windmill believes the forwarding headers of every + address in it, which is where your ingress or load balancer reaches it from. A host on + that network, a Windmill job included, can therefore name its own client address in audit + logs, for the login rate limit{#if $enterpriseLicense}{' '}and for token IP allowlists: a + leaked token stays restricted for an outsider, not for someone who can run a job{/if}. + List your proxies' addresses below to trust only them{#if ownProxy}, for example + <code>{ownProxy}</code>, the proxy this page came through, or its subnet{/if}. + </Alert> + {/if} + + <div class="flex flex-col gap-1 text-xs text-primary"> + <div> + <span class="text-secondary">This request:</span> + {#if status.peer} + connection from <code>{status.peer}</code>, recorded as + <code>{status.client_ip}</code> + {#if status.enforced_client_ip !== status.client_ip} + (token IP allowlists see <code>{status.enforced_client_ip}</code>) + {/if} + {:else} + the server cannot tell + {/if} + </div> + {#if status.attributed} + <div> + <span class="text-secondary">Trusted for audit entries and login rate limits:</span> + {describe(status.attributed)} + </div> + <div> + <span class="text-secondary">Trusted for token IP allowlists:</span> + {describe(status.enforced)} + </div> + {:else} + <div> + <span class="text-secondary">Trusted proxies:</span> + {describe(status.enforced)} + </div> + {/if} + {#if status.client_ip_header} + <div> + <span class="text-secondary">Client IP header:</span> + <code>{status.client_ip_header}</code> + </div> + {/if} + </div> + + {#if loading || !$values} + <Skeleton layout={[[2.5], 1, [2.5], 1, [2.5]]} /> + {:else} + <div class="flex flex-col gap-1"> + <label for="trusted_proxies" class="text-xs font-semibold text-emphasis"> + Trusted proxies + </label> + <div class="text-xs text-secondary"> + The proxies whose forwarding headers are believed, comma-separated: IP addresses, CIDRs, + hostnames (re-resolved every 15 seconds, such as a compose service) and + <code>private</code> for loopback and the private ranges. <code>none</code> trusts no proxy. + Empty trusts loopback and the private ranges. Never list Cloudflare's ranges here: turn on + Trust Cloudflare. + </div> + {#if trustedProxiesFromEnv} + {@render fromEnv( + 'TRUSTED_PROXIES', + configuration.trusted_proxies.value ?? '', + $values.trusted_proxies + )} + {:else} + <TextInput + inputProps={{ + type: 'text', + id: 'trusted_proxies', + placeholder: 'private (default)' + }} + bind:value={$values.trusted_proxies} + error={proxiesErrors.length > 0} + class="max-w-lg" + /> + {#each proxiesErrors as e, i (i)} + <span class="text-red-600 dark:text-red-400 text-2xs">{e}</span> + {/each} + {/if} + </div> + + <div class="flex flex-col gap-1"> + <span class="text-xs font-semibold text-emphasis">Trust Cloudflare</span> + <div class="text-xs text-secondary"> + Also believe Cloudflare's published ranges, and the <code>CF-Connecting-IP</code> they send, + for audit entries and login rate limits. Token IP allowlists never trust them: any Cloudflare + customer's Worker sends from those ranges with headers of its choosing. + </div> + {#if configuration.trust_cloudflare.from_env} + {@render fromEnv( + 'TRUST_CLOUDFLARE', + String(configuration.trust_cloudflare.value), + $values.trust_cloudflare + )} + {:else} + <Toggle + bind:checked={$values.trust_cloudflare} + id="trust_cloudflare" + ariaLabel="Trust Cloudflare" + /> + {/if} + </div> + + <div class="flex flex-col gap-1"> + <label for="client_ip_header" class="text-xs font-semibold text-emphasis"> + Client IP header + </label> + <div class="text-xs text-secondary"> + A header the edge in front of Windmill overwrites on every request, read instead of + <code>X-Forwarded-For</code>: <code>CloudFront-Viewer-Address</code>, + <code>CF-Connecting-IP</code>, or an nginx <code>X-Real-IP</code>. Leave it empty unless + the edge sets it on every request, or clients can name their own address. + </div> + {#if configuration.client_ip_header.from_env} + {@render fromEnv( + 'CLIENT_IP_HEADER', + configuration.client_ip_header.value ?? '', + $values.client_ip_header + )} + {:else} + <TextInput + inputProps={{ type: 'text', id: 'client_ip_header', placeholder: 'X-Forwarded-For' }} + bind:value={$values.client_ip_header} + error={headerError} + class="max-w-lg" + /> + {#if headerError} + <span class="text-red-600 dark:text-red-400 text-2xs">{headerError}</span> + {/if} + {/if} + </div> + {/if} + + {#if status.forwarders.length > 0} + <DataTable size="xs"> + <Head> + <tr> + <Cell head first>Peer sending forwarding headers</Cell> + <Cell head>Believed by</Cell> + <Cell head>Requests</Cell> + <Cell head last>Last seen</Cell> + </tr> + </Head> + <tbody> + {#each status.forwarders as f (f.peer)} + <tr> + <Cell first><span class="font-mono text-xs">{f.peer}</span></Cell> + <Cell> + {#if f.attributed_only} + <Badge color="blue">Audit and rate limits (Cloudflare)</Badge> + {:else} + <Badge color="red">Nothing</Badge> + {/if} + </Cell> + <Cell>{f.requests}</Cell> + <Cell last>{displayDate(f.last_seen)}</Cell> + </tr> + {/each} + </tbody> + </DataTable> + <div class="text-2xs text-secondary"> + Seen by the server answering this page since it started. A peer believed by nothing is + recorded as the client: either a proxy missing from the trusted proxies or a client sending + forwarding headers of its own, which are ignored. + </div> + {:else} + <div class="text-xs text-secondary"> + No request with forwarding headers from an untrusted peer since this server started. + </div> + {/if} + </div> +{/if} diff --git a/frontend/src/lib/components/instanceSettings/InstanceIpAllowlist.svelte b/frontend/src/lib/components/instanceSettings/InstanceIpAllowlist.svelte new file mode 100644 index 0000000000..ed7a0f5eed --- /dev/null +++ b/frontend/src/lib/components/instanceSettings/InstanceIpAllowlist.svelte @@ -0,0 +1,220 @@ +<script lang="ts"> + import type { Writable } from 'svelte/store' + import { resource } from 'runed' + import { SettingService, type ClientIpDiagnostics } from '$lib/gen' + import { Alert, Button } from '../common' + import Toggle from '../Toggle.svelte' + import Label from '../Label.svelte' + import { Plus } from 'lucide-svelte' + import { instanceSettingsSaved } from '../instanceSettings' + + interface Props { + values: Writable<Record<string, any>> + /** Without a valid license a stored list stays enforced, and may only be turned off. */ + licensed: boolean + } + + let { values, licensed }: Props = $props() + + const KEY = 'instance_ip_allowlist' + + const CATEGORIES = [ + { + key: 'webhooks', + label: 'Webhooks', + description: + 'Runs of a script or flow by path or hash called with a token (jobs/run, run_wait_result, run_and_stream), native trigger deliveries included, their results, resume and cancel links of approval steps, and webhook captures.' + }, + { key: 'http_routes', label: 'HTTP routes', description: 'Every route under /api/r/.' }, + { + key: 'push_callbacks', + label: 'Push and chat callbacks', + description: + 'GitHub and GitLab webhooks, GCP Pub/Sub and Azure Event Grid pushes, Slack and Teams callbacks. Native trigger deliveries are webhooks.' + }, + { + key: 'public_apps', + label: 'Public apps', + description: 'Public app pages and the runs they start (apps_u, jobs_u, resources_u).' + }, + { + key: 'health', + label: 'Health checks', + description: + '/api/version, /api/health/status and /api/min_keep_alive_version, for load balancers.' + }, + { + key: 'agent_workers', + label: 'Agent workers', + description: + 'The agent worker protocol, not the route that creates agent tokens. Their jobs reach the API with their job token, which always passes.' + } + ] as const + + type Form = { enabled: boolean; allowed: string; exempt: string[]; prefixes: string } + + const diagnostics = resource( + () => $instanceSettingsSaved, + (): Promise<ClientIpDiagnostics> => SettingService.getClientIpDiagnostics() + ) + let status = $derived(diagnostics.current) + let ownIp = $derived(status?.enforced_client_ip ?? undefined) + let trustExplicit = $derived(status ? !status.private_ranges_trusted : true) + let disabled = $derived(!licensed) + + function lines(s: string): string[] { + return s + .split(/[\n,]/) + .map((l) => l.trim()) + .filter((l) => l) + } + + type ExemptRule = { category?: string; path_prefix?: string; [field: string]: unknown } + + function toForm(v: any): Form { + const rules: ExemptRule[] = v?.exempt ?? [] + return { + enabled: v?.enabled ?? false, + allowed: (v?.allowed ?? []).join('\n'), + exempt: rules.flatMap((r) => (r.category ? [r.category] : [])), + prefixes: rules.flatMap((r) => (r.path_prefix ? [r.path_prefix] : [])).join('\n') + } + } + + // Each rule is rebuilt from the stored one when it is still selected, so fields this form + // does not edit survive a save. + function serialize(f: Form): any | undefined { + const allowed = lines(f.allowed) + const prefixes = lines(f.prefixes) + if (!f.enabled && allowed.length === 0 && f.exempt.length === 0 && prefixes.length === 0) { + return undefined + } + const stored: ExemptRule[] = $values[KEY]?.exempt ?? [] + const exempt: ExemptRule[] = [ + ...f.exempt.map((c) => stored.find((r) => r.category === c) ?? { category: c }), + ...prefixes.map((p) => stored.find((r) => r.path_prefix === p) ?? { path_prefix: p }) + ] + // Key order as jsonb stores it (shorter keys first), so an untouched list shows no diff. + return { exempt, allowed, enabled: f.enabled } + } + + let form = $state<Form>(toForm(undefined)) + let lastSynced: string | undefined = undefined + + $effect(() => { + const cur = JSON.stringify($values[KEY] ?? null) + if (cur === lastSynced) return + lastSynced = cur + form = toForm($values[KEY]) + }) + + $effect(() => { + const next = serialize(form) + if (lastSynced === undefined) return + const nextStr = JSON.stringify(next ?? null) + if (nextStr === JSON.stringify(serialize(toForm($values[KEY])) ?? null)) return + lastSynced = nextStr + $values[KEY] = next + }) + + let ownIpListed = $derived( + ownIp != undefined && lines(form.allowed).some((l) => l === ownIp || l === `${ownIp}/32`) + ) + + function toggleCategory(key: string, on: boolean) { + form.exempt = on ? [...new Set([...form.exempt, key])] : form.exempt.filter((k) => k !== key) + } +</script> + +<div class="flex flex-col gap-4 p-4 rounded-md border"> + {#if !trustExplicit} + <Alert type="warning" title="Name your trusted proxies first"> + The allowlist needs your reverse proxies named in Trusted proxies above, and saved, none of them + a whole private range such as 10.0.0.0/8: every host of a trusted network, a Windmill job + included, could claim an allowlisted address. + </Alert> + {/if} + {#if status?.attributed?.cloudflare} + <Alert type="info" title="Behind Cloudflare, this list sees the Cloudflare edge"> + Cloudflare's ranges are trusted for audit entries only: anyone can put their own Cloudflare + zone in front of your origin and send it any <code>CF-Connecting-IP</code>. To restrict who + reaches an origin behind Cloudflare, use Cloudflare Access or authenticated origin pulls. + </Alert> + {/if} + + <Toggle + bind:checked={form.enabled} + disabled={!form.enabled && (disabled || !trustExplicit)} + options={{ + right: 'Only accept API requests from the addresses below', + rightTooltip: + "Checked before authentication, against the client IP that token IP allowlists use. Windmill's own traffic always passes: loopback, the trusted proxies, worker processes and requests carrying a job token." + }} + /> + + <Label label="Allowed IPs and CIDRs"> + <textarea + rows="4" + {disabled} + placeholder={'203.0.113.0/24\n2001:db8::/48'} + bind:value={form.allowed} + ></textarea> + <div class="flex items-center gap-2 text-2xs text-secondary"> + {#if ownIp} + <span>This request comes from <code>{ownIp}</code>.</span> + {#if !ownIpListed} + <Button + unifiedSize="xs" + variant="subtle" + startIcon={{ icon: Plus }} + {disabled} + onclick={() => (form.allowed = [...lines(form.allowed), ownIp].join('\n'))} + > + Add it + </Button> + {/if} + {/if} + <span + >A list that leaves out your own address is refused, so saving it cannot lock you out.</span + > + </div> + </Label> + + <div class="flex flex-col gap-2"> + <span class="text-xs font-semibold text-emphasis">Reachable from anywhere</span> + <span class="text-xs text-secondary"> + What outside systems call. Each still needs its own token or secret. Browser sign-in callbacks + come from the user's address and need no exemption. + </span> + {#each CATEGORIES as c (c.key)} + <Toggle + size="xs" + {disabled} + checked={form.exempt.includes(c.key)} + on:change={(e) => toggleCategory(c.key, e.detail)} + options={{ right: c.label, rightTooltip: c.description }} + /> + {/each} + </div> + + <Label label="Other path prefixes reachable from anywhere"> + <textarea + rows="2" + {disabled} + placeholder="/api/w/main/jobs/run/p/u/admin/webhook" + bind:value={form.prefixes} + ></textarea> + <span class="text-2xs text-hint" + >One per line, under /api/, matched on whole path segments.</span + > + </Label> + + <div class="text-2xs text-secondary"> + Locked out? Restart the server with <code>INSTANCE_IP_ALLOWLIST_DISABLED=true</code>, or turn it + off in the database, which every server picks up within seconds: + <code + >UPDATE global_settings SET value = jsonb_set(value, '{'{'}enabled{'}'}', 'false') WHERE name + = 'instance_ip_allowlist';</code + > + </div> +</div> diff --git a/frontend/src/lib/components/instanceSettings/OtelAuditLogsSettings.svelte b/frontend/src/lib/components/instanceSettings/OtelAuditLogsSettings.svelte new file mode 100644 index 0000000000..f852bd9dd5 --- /dev/null +++ b/frontend/src/lib/components/instanceSettings/OtelAuditLogsSettings.svelte @@ -0,0 +1,95 @@ +<script lang="ts"> + import type { Writable } from 'svelte/store' + import Toggle from '../Toggle.svelte' + import TextInput from '../text_input/TextInput.svelte' + import Select from '../select/Select.svelte' + import OtelAuditWorkspaces from './OtelAuditWorkspaces.svelte' + + interface Props { + values: Writable<Record<string, any>> + disabled?: boolean + } + + let { values, disabled = false }: Props = $props() +</script> + +{#if $values.otel} + {#if $values.otel.logs_enabled} + <Toggle + {disabled} + id="logs_exclude_audit" + bind:checked={$values.otel.logs_exclude_audit} + options={{ + right: 'Leave audit logs out of the logs export', + rightTooltip: 'For when the audit logs export below carries them.' + }} + /> + {/if} + + <div class="flex flex-col gap-4 pt-4 border-t"> + <div class="flex flex-col gap-1"> + <span class="text-xs font-semibold text-emphasis">Audit logs export</span> + <span class="text-2xs text-secondary"> + A second logs exporter that receives audit logs only, whatever the log level, for example to + keep them in long-term storage. It has its own endpoint and headers. + </span> + </div> + <Toggle + {disabled} + id="audit_logs_enabled" + bind:checked={$values.otel.audit_logs_enabled} + options={{ right: 'Export audit logs' }} + /> + {#if $values.otel.audit_logs_enabled} + <div class="flex flex-col gap-1"> + <label for="OTEL_AUDIT_LOGS_ENDPOINT" class="block text-xs font-semibold text-emphasis" + >Endpoint</label + > + <TextInput + inputProps={{ + type: 'text', + placeholder: 'https://audit-collector.example.com:4317', + id: 'OTEL_AUDIT_LOGS_ENDPOINT', + disabled + }} + bind:value={$values.otel.audit_logs_endpoint} + /> + </div> + <div class="flex flex-col gap-1"> + <label for="OTEL_AUDIT_LOGS_HEADERS" class="block text-xs font-semibold text-emphasis" + >Headers</label + > + <TextInput + inputProps={{ + type: 'text', + placeholder: 'Authorization=Bearer my-secret-token', + id: 'OTEL_AUDIT_LOGS_HEADERS', + disabled + }} + bind:value={$values.otel.audit_logs_headers} + /> + </div> + <div class="flex flex-col gap-1"> + <label for="OTEL_AUDIT_LOGS_PROTOCOL" class="block text-xs font-semibold text-emphasis" + >Protocol</label + > + <Select + id="OTEL_AUDIT_LOGS_PROTOCOL" + {disabled} + clearable + placeholder="grpc (default)" + items={[{ label: 'http/protobuf', value: 'http/protobuf' }]} + bind:value={$values.otel.audit_logs_protocol} + /> + </div> + <div class="flex flex-col gap-1"> + <span class="block text-xs font-semibold text-emphasis">Workspaces</span> + <span class="text-2xs text-secondary"> + Export the audit logs of these workspaces only. Instance-level entries are always + exported. Leave empty for all workspaces. + </span> + <OtelAuditWorkspaces bind:value={$values.otel.audit_logs_workspaces} {disabled} /> + </div> + {/if} + </div> +{/if} diff --git a/frontend/src/lib/components/instanceSettings/OtelAuditWorkspaces.svelte b/frontend/src/lib/components/instanceSettings/OtelAuditWorkspaces.svelte new file mode 100644 index 0000000000..766bb25b01 --- /dev/null +++ b/frontend/src/lib/components/instanceSettings/OtelAuditWorkspaces.svelte @@ -0,0 +1,40 @@ +<script lang="ts"> + import { WorkspaceService } from '$lib/gen' + import MultiSelect from '$lib/components/select/MultiSelect.svelte' + import { safeSelectItems } from '$lib/components/select/utils.svelte' + import { resource } from 'runed' + + interface Props { + /** Empty exports every workspace's audit events. Cleared to `[]`, not unset: unset + * falls back to the OTEL_AUDIT_LOGS_WORKSPACES environment variable. */ + value: string[] | undefined + disabled?: boolean + } + + let { value = $bindable(), disabled = false }: Props = $props() + + const workspaces = resource( + () => undefined, + async () => { + const all: string[] = [] + for (let page = 1; ; page++) { + const batch = await WorkspaceService.listWorkspacesAsSuperAdmin({ page, perPage: 100 }) + all.push(...batch.map((w) => w.id)) + if (batch.length < 100) break + } + return all + } + ) + + // Workspaces already listed stay selectable even when they no longer exist. + let items = $derived( + safeSelectItems([...new Set([...(workspaces.current ?? []), ...(value ?? [])])]) + ) +</script> + +<MultiSelect + {items} + {disabled} + placeholder="All workspaces" + bind:value={() => value ?? [], (v) => (value = v)} +/> diff --git a/frontend/src/lib/components/instanceSettings/TokenReview.svelte b/frontend/src/lib/components/instanceSettings/TokenReview.svelte new file mode 100644 index 0000000000..42f1948296 --- /dev/null +++ b/frontend/src/lib/components/instanceSettings/TokenReview.svelte @@ -0,0 +1,256 @@ +<script lang="ts"> + import DataTable from '$lib/components/table/DataTable.svelte' + import Head from '$lib/components/table/Head.svelte' + import Cell from '$lib/components/table/Cell.svelte' + import SettingsPageHeader from '$lib/components/settings/SettingsPageHeader.svelte' + import Select from '$lib/components/select/Select.svelte' + import TextInput from '$lib/components/text_input/TextInput.svelte' + import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte' + import { Alert, Badge, Button } from '$lib/components/common' + import { UserService, type TokenForReview, type TokenRisk, type TokenRiskCounts } from '$lib/gen' + import { displayDate } from '$lib/utils' + import { sendUserToast } from '$lib/toast' + import { Trash } from 'lucide-svelte' + import { Debounced, watch } from 'runed' + import { + tokenRiskSummary, + TOKEN_RISK_INFO, + TOKEN_RISKS + } from '$lib/components/settings/tokenRisks' + import { MCP_SESSION } from '$lib/components/mcp/McpAccessPicker.svelte' + import { enterpriseLicense } from '$lib/stores' + + const perPage = 100 + + let tokens: TokenForReview[] = $state([]) + let counts: TokenRiskCounts | undefined = $state(undefined) + let hasMore = $state(false) + let loading = $state(false) + let loadFailed = $state(false) + let flagFilter: TokenRisk | 'any' | 'all' = $state('any') + let search = $state('') + const debouncedSearch = new Debounced(() => search.trim(), 300) + let toDelete: TokenForReview | undefined = $state(undefined) + let deleting = $state(false) + // Drops a response that a newer filter or search has overtaken. + let requestId = 0 + // The last row the server returned, which the shown list may have dropped as a repeat: a + // cursor taken from the shown list would stall on a page of repeats. + let cursor: TokenForReview | undefined = undefined + + async function loadCounts() { + try { + counts = await UserService.getTokenRiskCountsAsSuperAdmin() + loadFailed = false + } catch (e) { + loadFailed = true + sendUserToast(`Failed to count tokens: ${e}`, true) + } + } + loadCounts() + + async function load(more: boolean) { + const id = ++requestId + const last = more ? cursor : undefined + loading = true + try { + const page = await UserService.listTokensAsSuperAdmin({ + flag: flagFilter === 'any' ? undefined : flagFilter, + search: debouncedSearch.current || undefined, + perPage, + afterLastUsedAt: last?.last_used_at, + afterTokenPrefix: last?.token_prefix + }) + if (id !== requestId) return + if (more) { + // A token used since the previous page moved behind the cursor and comes back. + const seen = new Set(tokens.map((t) => `${t.email}:${t.token_prefix}`)) + tokens = [...tokens, ...page.filter((t) => !seen.has(`${t.email}:${t.token_prefix}`))] + } else { + tokens = page + } + if (page.length > 0) cursor = page[page.length - 1] + hasMore = page.length === perPage + } catch (e) { + if (id !== requestId) return + sendUserToast(`Failed to load tokens: ${e}`, true) + } finally { + if (id === requestId) loading = false + } + } + + watch([() => $enterpriseLicense, () => flagFilter, () => debouncedSearch.current], () => { + if ($enterpriseLicense) load(false) + }) + + let riskSummary = $derived(tokenRiskSummary(counts)) + let flagItems = $derived([ + { value: 'any', label: 'Any flag' }, + ...TOKEN_RISKS.map((r) => ({ + value: r, + label: counts ? `${TOKEN_RISK_INFO[r].badge} (${counts[r]})` : TOKEN_RISK_INFO[r].badge + })), + { value: 'all', label: 'All tokens' } + ]) + + function shownScopes(scopes: string[] | undefined): string { + return (scopes ?? []).filter((s) => s !== MCP_SESSION).join(', ') + } + + async function confirmDelete() { + const t = toDelete + if (!t?.email) return + deleting = true + try { + await UserService.deleteTokenAsSuperAdmin({ email: t.email, tokenPrefix: t.token_prefix }) + tokens = tokens.filter((x) => !(x.email === t.email && x.token_prefix === t.token_prefix)) + if (counts) { + const next = { ...counts } + for (const r of t.risks) next[r] = Math.max(0, next[r] - 1) + counts = next + } + sendUserToast(`Deleted token ${t.token_prefix}**** of ${t.email}`) + toDelete = undefined + } catch (e) { + sendUserToast(`Failed to delete token: ${e}`, true) + } finally { + deleting = false + } + } +</script> + +<SettingsPageHeader + title="Token review" + description="API tokens of every user on the instance, least recently used first. Tokens the server expires or renews on its own (login sessions, job, app, MCP and impersonation tokens) are left out." +/> + +{#if riskSummary.length > 0} + <div class="mb-4"> + <Alert type="warning" size="xs" title="Tokens to review across the instance"> + <ul class="list-disc pl-4"> + {#each riskSummary as line (line)} + <li>{line}</li> + {/each} + </ul> + </Alert> + </div> +{:else if counts && !loadFailed} + <div class="mb-4"> + <Alert type="success" size="xs" title="No token needs a review" /> + </div> +{/if} + +{#if !$enterpriseLicense} + <Alert type="info" size="xs" title="The token list requires Enterprise Edition"> + With an Enterprise license, this page lists every user's tokens, filters them by flag, owner + or label, and deletes any of them. + </Alert> +{:else} + <div class="flex flex-row gap-2 items-center mb-2"> + <TextInput + inputProps={{ placeholder: 'Search by email or label' }} + bind:value={search} + class="w-60" + /> + <Select items={flagItems} bind:value={flagFilter} class="w-52" /> + </div> + + <DataTable loading={loading && tokens.length === 0}> + <Head> + <tr> + <Cell head first>Owner</Cell> + <Cell head>Token</Cell> + <Cell head>Flags</Cell> + <Cell head>Workspace</Cell> + <Cell head>Scopes</Cell> + <Cell head>Last used</Cell> + <Cell head>Expiration</Cell> + <Cell head last></Cell> + </tr> + </Head> + <tbody> + {#each tokens as token, i (`${token.email}:${token.token_prefix}`)} + <tr class={i % 2 === 0 ? 'bg-surface-tertiary' : 'bg-surface'}> + <Cell first><span class="text-xs">{token.email ?? '-'}</span></Cell> + <Cell> + <div class="flex flex-col"> + <span class="font-mono text-xs">{token.token_prefix}****</span> + <span class="text-2xs text-secondary truncate max-w-40" title={token.label ?? ''} + >{token.label ?? ''}</span + > + </div> + </Cell> + <Cell> + <div class="flex flex-wrap gap-1"> + {#if token.read_only} + <Badge color="blue" small>Read-only</Badge> + {/if} + {#each token.risks as risk (risk)} + <span title={TOKEN_RISK_INFO[risk].tooltip}> + <Badge color={TOKEN_RISK_INFO[risk].color} small + >{TOKEN_RISK_INFO[risk].badge}</Badge + > + </span> + {/each} + </div> + </Cell> + <Cell><span class="text-xs">{token.workspace_id ?? 'All'}</span></Cell> + <Cell> + <span class="text-xs truncate max-w-48 block" title={shownScopes(token.scopes)} + >{shownScopes(token.scopes) || '-'}</span + > + </Cell> + <Cell><span class="whitespace-nowrap text-xs">{displayDate(token.last_used_at)}</span></Cell + > + <Cell> + <span class="whitespace-nowrap text-xs" + >{token.expiration ? displayDate(token.expiration) : 'Never'}</span + > + </Cell> + <Cell last> + <Button + variant="subtle" + destructive + unifiedSize="xs" + title="Delete token" + startIcon={{ icon: Trash }} + iconOnly + disabled={!token.email} + onclick={() => (toDelete = token)} + /> + </Cell> + </tr> + {:else} + {#if !loading} + <tr> + <Cell first last colspan={8}> + <span class="text-secondary italic text-xs"> + {flagFilter === 'all' ? 'No tokens' : 'No token has this flag'} + </span> + </Cell> + </tr> + {/if} + {/each} + </tbody> + </DataTable> + + {#if hasMore} + <div class="flex justify-center mt-2"> + <Button variant="default" unifiedSize="sm" {loading} onclick={() => load(true)}> + Load more + </Button> + </div> + {/if} +{/if} + +<ConfirmationModal + open={toDelete !== undefined} + title="Delete token" + confirmationText="Delete" + loading={deleting} + onConfirmed={confirmDelete} + onCanceled={() => (toDelete = undefined)} +> + The token {toDelete?.token_prefix}**** {toDelete?.label ? `(${toDelete.label}) ` : ''}of + {toDelete?.email} stops working immediately. Anything authenticating with it will fail. +</ConfirmationModal> diff --git a/frontend/src/lib/components/mcp/ownServers.ts b/frontend/src/lib/components/mcp/ownServers.ts index 31c860a039..85df510956 100644 --- a/frontend/src/lib/components/mcp/ownServers.ts +++ b/frontend/src/lib/components/mcp/ownServers.ts @@ -1,6 +1,7 @@ import { get } from 'svelte/store' import { userStore } from '$lib/stores' import { getWorkspaceRole } from '$lib/user' +import { ResourceService } from '$lib/gen' /** The principals an `extra_perms` entry can name to grant this user access. */ export type McpViewer = { username: string | undefined; pgroups: string[] } @@ -46,3 +47,16 @@ export async function mcpViewer(workspace: string): Promise<McpViewer> { } return { username: undefined, pgroups: [] } } + +/** The workspace's `mcp` resources the chat may list for this viewer, on or off. */ +export async function listVisibleMcpServers( + workspace: string +): Promise<{ path: string; editedAt?: string }[]> { + const [resources, viewer] = await Promise.all([ + ResourceService.listResource({ workspace, resourceType: 'mcp', perPage: MCP_LIST_PER_PAGE }), + mcpViewer(workspace) + ]) + return resources + .filter((r) => isOwnOrSharedMcpPath(r.path, r.extra_perms, viewer)) + .map((r) => ({ path: r.path, editedAt: r.edited_at })) +} diff --git a/frontend/src/lib/components/meltComponents/Popover.svelte b/frontend/src/lib/components/meltComponents/Popover.svelte index 0ba7b647ab..cc706e7d50 100644 --- a/frontend/src/lib/components/meltComponents/Popover.svelte +++ b/frontend/src/lib/components/meltComponents/Popover.svelte @@ -242,10 +242,14 @@ <svelte:window onkeydown={(e) => isOpen && hostActive() && onKeyDown(e)} /> +<!-- aria-expanded and data-state are set here: melt derives them from `forceVisible`, which is +always on, so its own values call a closed popover open. --> <button class={className} use:melt={$_trigger} aria-label="Popup button" + aria-expanded={isOpen} + data-state={isOpen ? 'open' : 'closed'} {...triggerAttrs} disabled={disablePopup || disabled} onmouseenter={() => { diff --git a/frontend/src/lib/components/offboarding-utils.ts b/frontend/src/lib/components/offboarding-utils.ts index 11f266e101..b920979b7f 100644 --- a/frontend/src/lib/components/offboarding-utils.ts +++ b/frontend/src/lib/components/offboarding-utils.ts @@ -1,4 +1,25 @@ -import type { OffboardAffectedPaths } from '$lib/gen' +import { + AiEvalsService, + AmqpTriggerService, + AppService, + AzureTriggerService, + EmailTriggerService, + FlowService, + GcpTriggerService, + HttpTriggerService, + KafkaTriggerService, + MqttTriggerService, + NatsTriggerService, + PostgresTriggerService, + ResourceService, + ScheduleService, + ScriptService, + SqsTriggerService, + VariableService, + WebsocketTriggerService, + type OffboardAffectedPaths, + type OffboardPathConflict +} from '$lib/gen' export function pl(n: number, singular: string): string { return `${n} ${singular}${n === 1 ? '' : 's'}` @@ -115,3 +136,85 @@ export function downloadCsv(rows: string[][], filename: string) { a.click() URL.revokeObjectURL(url) } + +type DeleteFn = (p: { workspace: string; path: string }) => Promise<unknown> + +// Keyed by the table names the offboarding conflict check reports. Scripts and flows are +// deleted rather than archived: an archived item still holds its path and keeps the conflict. +const DELETE_BY_KIND: Record<string, DeleteFn> = { + script: (p) => ScriptService.deleteScriptByPath(p), + flow: (p) => FlowService.deleteFlowByPath(p), + app: (p) => AppService.deleteApp(p), + resource: (p) => ResourceService.deleteResource(p), + variable: (p) => VariableService.deleteVariable(p), + schedule: (p) => ScheduleService.deleteSchedule(p), + eval_dataset: (p) => AiEvalsService.deleteEvalDataset(p), + http_trigger: (p) => HttpTriggerService.deleteHttpTrigger(p), + websocket_trigger: (p) => WebsocketTriggerService.deleteWebsocketTrigger(p), + kafka_trigger: (p) => KafkaTriggerService.deleteKafkaTrigger(p), + postgres_trigger: (p) => PostgresTriggerService.deletePostgresTrigger(p), + mqtt_trigger: (p) => MqttTriggerService.deleteMqttTrigger(p), + amqp_trigger: (p) => AmqpTriggerService.deleteAmqpTrigger(p), + nats_trigger: (p) => NatsTriggerService.deleteNatsTrigger(p), + sqs_trigger: (p) => SqsTriggerService.deleteSqsTrigger(p), + gcp_trigger: (p) => GcpTriggerService.deleteGcpTrigger(p), + azure_trigger: (p) => AzureTriggerService.deleteAzureTrigger(p), + email_trigger: (p) => EmailTriggerService.deleteEmailTrigger(p) +} + +const TRASHED_KINDS = new Set(['script', 'flow', 'app', 'resource', 'variable', 'schedule']) + +export function canDeleteKind(kind: string): boolean { + return kind in DELETE_BY_KIND +} + +export function isTrashedKind(kind: string): boolean { + return TRASHED_KINDS.has(kind) +} + +export async function deleteItemOfKind( + kind: string, + workspace: string, + path: string +): Promise<void> { + const del = DELETE_BY_KIND[kind] + if (!del) throw new Error(`Cannot delete items of kind ${kind}`) + await del({ workspace, path }) +} + +export function withoutConflict( + conflicts: OffboardPathConflict[], + resolved: OffboardPathConflict +): OffboardPathConflict[] { + return conflicts.filter( + (c) => + !( + c.workspace_id === resolved.workspace_id && + c.kind === resolved.kind && + c.source_path === resolved.source_path + ) + ) +} + +/** + * Deleting a resource also deletes the variables linked to it, which can remove one side of a + * variable conflict. Returns the remaining conflicts that no longer have both sides, so the list + * does not offer to "keep" an item that is already gone. + */ +export async function conflictsGoneAfterDelete( + deletedKind: string, + remaining: OffboardPathConflict[] +): Promise<OffboardPathConflict[]> { + if (deletedKind !== 'resource') return [] + const variables = remaining.filter((c) => c.kind === 'variable') + const gone = await Promise.all( + variables.map(async (c) => { + const [source, target] = await Promise.all([ + VariableService.existsVariable({ workspace: c.workspace_id, path: c.source_path }), + VariableService.existsVariable({ workspace: c.workspace_id, path: c.target_path }) + ]) + return !source || !target + }) + ) + return variables.filter((_, i) => gone[i]) +} diff --git a/frontend/src/lib/components/progressBar/ProgressBar.svelte b/frontend/src/lib/components/progressBar/ProgressBar.svelte index 77e21dc205..c2c7d7ed85 100644 --- a/frontend/src/lib/components/progressBar/ProgressBar.svelte +++ b/frontend/src/lib/components/progressBar/ProgressBar.svelte @@ -2,7 +2,7 @@ import { Tween } from 'svelte/motion' import { linear } from 'svelte/easing' import { twMerge } from 'tailwind-merge' - import { Loader2 } from 'lucide-svelte' + import { Hourglass, Loader2 } from 'lucide-svelte' import { fade } from 'svelte/transition' import type { Snippet } from 'svelte' @@ -37,6 +37,8 @@ isScheduled?: boolean // Whether the job was skipped (early-stop labelled as skipped) isSkipped?: boolean + /** Why the next step has not started yet, e.g. a sleep or a concurrency limit. */ + waitingText?: string /** Rendered after "Error occurred" when the bar is in its error state. */ errorAction?: Snippet } @@ -60,6 +62,7 @@ isCanceled = false, isScheduled = false, isSkipped = false, + waitingText = undefined, errorAction }: Props = $props() let duration = 200 @@ -92,6 +95,9 @@ const status: 'error' | 'done' | 'running' = $derived( error != undefined ? 'error' : finished ? 'done' : 'running' ) + // Violet like a suspended run everywhere else (badges, Recently run). + let waiting = $derived(status == 'running' && isWaitingForEvents && !isCanceled) + let fill = $derived(waiting ? 'bg-violet-400' : 'bg-blue-400') </script> <div class={twMerge('flex flex-col gap-1', className)}> @@ -127,14 +133,14 @@ {/if} {#if partIndex < index - 1} <div - class="absolute left-0 bottom-0 h-full w-full bg-blue-400 transition-colors duration-300 ease-in-out" + class="absolute left-0 bottom-0 h-full w-full {fill} transition-colors duration-300 ease-in-out" ></div> {:else if partIndex == index - 1 || (partIndex == index && subIndex !== undefined) || error == partIndex} <div class="absolute left-0 bottom-0 h-full transition-all duration-300 ease-in-out {error == partIndex ? 'bg-red-400' - : 'bg-blue-400'}" + : fill}" style="width: {getPercent(partIndex, percent.current)}%" ></div> {/if} @@ -153,13 +159,17 @@ class="flex justify-between items-end font-medium transition-colors duration-300 ease-in-out {error != undefined || isCanceled ? 'text-red-600 dark:text-red-400' - : 'text-blue-700 dark:text-blue-200'}" + : waiting + ? 'text-violet-600 dark:text-violet-400' + : 'text-blue-700 dark:text-blue-200'}" > <div class={twMerge(slim ? 'text-xs' : 'text-sm', 'flex items-center gap-1')}> - {#if status == 'running' && !isCanceled && !isScheduled && !isSkipped} + {#if waiting} + <Hourglass size={14} /> + {:else if status == 'running' && !isCanceled && !isScheduled && !isSkipped} <Loader2 class="animate-spin" size={14} /> {/if} - {#key status + isWaitingForEvents + stepId + isCanceled + isScheduled + isSkipped} + {#key status + isWaitingForEvents + stepId + isCanceled + isScheduled + isSkipped + waitingText} <span in:fade={{ duration: 150 }}> {#if status == 'error'} Error occurred @@ -173,9 +183,11 @@ Waiting to be resumed {:else if isScheduled} (not started) + {:else if waitingText} + {waitingText} {:else if showStepId} {stepId - ? `${isCanceled ? 'Canceled at' : 'Running'} step ${stepId}` + ? `${isCanceled ? 'Canceled at' : 'Running'} step '${stepId}'` : `${isCanceled ? 'Canceled' : ''}`} {:else if hideStepTitle} {isCanceled ? 'Canceled' : 'Running'} diff --git a/frontend/src/lib/components/propertyPicker/ObjectViewer.svelte b/frontend/src/lib/components/propertyPicker/ObjectViewer.svelte index d9684430c5..1102ea7165 100644 --- a/frontend/src/lib/components/propertyPicker/ObjectViewer.svelte +++ b/frontend/src/lib/components/propertyPicker/ObjectViewer.svelte @@ -51,6 +51,10 @@ connecting?: boolean metaData?: Snippet<[any]> editKey?: Snippet<[any]> + /** Keep each value on its key's line and widen the tree to its widest row, scrolling + * sideways. Off, a long value wraps, which narrow panels (the flow pickers) rely on to + * avoid a horizontal scrollbar. */ + wideRows?: boolean } let { @@ -67,7 +71,8 @@ expandedEvenOnLevel0 = undefined, connecting = false, metaData, - editKey + editKey, + wideRows = false }: Props = $props() let jsonFiltered = $state(untrack(() => json)) @@ -281,7 +286,7 @@ {/if} {#if level == 0} - <div class="float-right"> + {#snippet searchControl()} {#if searchOpen} <div class="px-1 relative"> <input @@ -317,7 +322,21 @@ }} ></Button> {/if} - </div> + {/snippet} + {#if wideRows} + <!-- Sticky, so it stays at the right edge when a wide value scrolls the viewer sideways. No + height, so it overlays the first line rather than taking room on it, which pushed a long + first value onto the next line. --> + <div class="float-right sticky right-0 z-[1] h-0 overflow-visible"> + <div class="bg-surface rounded-md"> + {@render searchControl()} + </div> + </div> + {:else} + <div class="float-right"> + {@render searchControl()} + </div> + {/if} {/if} {#if keys.length > 0} @@ -475,7 +494,15 @@ {#if level === 0} <ContextMenu items={menuItems}> - {@render viewerContent()} + {#if wideRows} + <!-- As wide as the widest row, so a long value widens every row (and its hover) instead of + running past it, and the sticky search button has the full width to stay in --> + <div class="w-max min-w-full"> + {@render viewerContent()} + </div> + {:else} + {@render viewerContent()} + {/if} </ContextMenu> {:else} {@render viewerContent()} diff --git a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte index 20c3ff1e74..0f70023b7b 100644 --- a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte @@ -36,10 +36,11 @@ rawAppStorageKey, rawAppCtx, readRawAppStorage, - applyRawAppStorageOp + applyRawAppStorageOp, + uiBuilderFiles } from './utils' import { runDomQueryOnHtml, type RawAppDomQuery, type RawAppDomRequester } from './rawAppDom' - import InlineElementPrompt from './InlineElementPrompt.svelte' + import InlinePrompt from '../copilot/chat/InlinePrompt.svelte' import DarkModeObserver from '../DarkModeObserver.svelte' import { getAppliedDarkModeVariant, type DarkModeVariant } from '$lib/darkModeVariant' import RawAppSidebar from './RawAppSidebar.svelte' @@ -86,6 +87,7 @@ import { sendUserToast } from '$lib/utils' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' import { UserDraft } from '$lib/userDraft.svelte' + import { assertDraftSaved } from '$lib/components/sessions/pageDrawerSession' import { setOpenInSessionHandoff } from '$lib/components/sessions/openInSessionContext' import { openSourceInSession } from '$lib/components/sessions/sessionSwitch.svelte' import { @@ -301,14 +303,12 @@ // discardIf baseline, safe only when there is none. async function persistDraftForSession(): Promise<void> { if (!opWorkspace || draftStoragePath === undefined) return - await UserDraftDbSyncer.flush({ - workspace: opWorkspace, - itemKind: 'raw_app', - path: draftStoragePath - }) + const query = { workspace: opWorkspace, itemKind: 'raw_app' as const, path: draftStoragePath } + await UserDraftDbSyncer.flush(query) if (newApp) { await UserDraft.forcePersist('raw_app', draftStoragePath, { workspace: opWorkspace }) } + assertDraftSaved(query) } const sessionOpen = $derived( @@ -1079,9 +1079,7 @@ addEventListener('message', function (e) { iframeFiles = { ...newFiles } iframeFocusPending = undefined buildTracker.start() - const files = Object.fromEntries( - Object.entries(newFiles).filter(([path, _]) => !path.endsWith('/')) - ) + const files = uiBuilderFiles(newFiles) target.postMessage( { type: 'setFiles', @@ -1099,9 +1097,7 @@ addEventListener('message', function (e) { const focus = iframeFocusPending === pathToSelect iframeFocusPending = undefined buildTracker.start() - const files = Object.fromEntries( - Object.entries(newFiles).filter(([path, _]) => !path.endsWith('/')) - ) + const files = uiBuilderFiles(newFiles) target.postMessage( { type: 'setFilesAndSelect', @@ -2212,7 +2208,7 @@ addEventListener('message', function (e) { await openSourceInSession(sessionOpen, { seedPrompt: prompt, autoSend: true, - seedDomElement: createAppDomSelectorElement({ + seedPick: createAppDomSelectorElement({ selector, appPath: sessionOpen.target.path, tagName: el.tagName, @@ -3181,11 +3177,10 @@ addEventListener('message', function (e) { (fresh value + autofocus); repositioning on scroll keeps the same key so it never steals focus mid-scroll. --> {#key inlinePromptSelector} - <InlineElementPrompt - x={inlinePromptPos.x} - y={inlinePromptPos.y} - label={inlinePromptLabel} - inNewSession={!onInlinePrompt} + <InlinePrompt + position={inlinePromptPos} + ariaLabel="Prompt about the selected element" + label={onInlinePrompt ? inlinePromptLabel : undefined} onSend={async (prompt) => { if ((await inlinePrompt?.(inlinePromptSelector!, prompt)) === false) return false inlinePromptDismissed = true diff --git a/frontend/src/lib/components/raw_apps/RawAppInlineScriptEditor.svelte b/frontend/src/lib/components/raw_apps/RawAppInlineScriptEditor.svelte index 844a447d51..23a7cf5ddb 100644 --- a/frontend/src/lib/components/raw_apps/RawAppInlineScriptEditor.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppInlineScriptEditor.svelte @@ -719,6 +719,7 @@ cmdEnterAction={() => onRun()} bind:websocketAlive rawAppRunnableKey={id} + codeSource={{ kind: 'raw_app', path, part: id }} on:change={async (e) => { if (inlineScript) { if (inlineScript.lock != undefined) { @@ -770,6 +771,7 @@ cmdEnterAction={() => onRun()} bind:websocketAlive rawAppRunnableKey={id} + codeSource={{ kind: 'raw_app', path, part: id }} on:change={async (e) => { if (inlineScript) { if (inlineScript.lock != undefined) { diff --git a/frontend/src/lib/components/raw_apps/utils.test.ts b/frontend/src/lib/components/raw_apps/utils.test.ts index dd55ea666c..10fb706543 100644 --- a/frontend/src/lib/components/raw_apps/utils.test.ts +++ b/frontend/src/lib/components/raw_apps/utils.test.ts @@ -10,6 +10,7 @@ import { rawAppCtx, rawAppPreviewModules, stripRawAppDiffNoise, + uiBuilderFiles, type Runnable } from './utils' @@ -290,3 +291,20 @@ describe('canonicalRawAppDiffValue', () => { expect(b.summary).toBe('app EDITED') }) }) + +describe('uiBuilderFiles', () => { + it('keeps app sources and drops directory entries and node_modules files', () => { + expect( + uiBuilderFiles({ + '/index.tsx': 'a', + '/src/node_modules_helper.ts': 'b', + '/src/': '', + '/node_modules/tailwindcss/dist/lib.mjs': 'x', + 'node_modules/pkg/index.js': 'x', + './node_modules/pkg/index.js': 'x', + '/src/vendor/node_modules/pkg/index.js': 'x', + '\\node_modules\\pkg\\index.js': 'x' + }) + ).toEqual({ '/index.tsx': 'a', '/src/node_modules_helper.ts': 'b' }) + }) +}) diff --git a/frontend/src/lib/components/raw_apps/utils.ts b/frontend/src/lib/components/raw_apps/utils.ts index 25b64615eb..99e47041c6 100644 --- a/frontend/src/lib/components/raw_apps/utils.ts +++ b/frontend/src/lib/components/raw_apps/utils.ts @@ -448,6 +448,25 @@ function hiddenRunnableToTsType(runnable: Runnable) { } } +function isNodeModulesPath(path: string): boolean { + return path + .replace(/^(\.?\/)+/, '') + .split(/[/\\]/) + .includes('node_modules') +} + +/** + * The app's stored files as the UI Builder bundler is given them. Its packages come from its + * own install into `node_modules/`, so a stored file under any `node_modules` segment would + * be imported in place of the installed package: such keys, like directory entries, are not + * app sources and stay out. + */ +export function uiBuilderFiles(files: Record<string, string>): Record<string, string> { + return Object.fromEntries( + Object.entries(files).filter(([path]) => !path.endsWith('/') && !isNodeModulesPath(path)) + ) +} + /** Shown in the file tree, generated by `genWmillTs` — never a key of `files`. */ export const WMILL_TS_PATH = '/wmill.ts' diff --git a/frontend/src/lib/components/recording/rawAppRecordingLoad.test.ts b/frontend/src/lib/components/recording/rawAppRecordingLoad.test.ts index a02c3744c9..85816c86db 100644 --- a/frontend/src/lib/components/recording/rawAppRecordingLoad.test.ts +++ b/frontend/src/lib/components/recording/rawAppRecordingLoad.test.ts @@ -4,7 +4,7 @@ * payload and renders it. Each rejection below is a way a caller-supplied recording * could otherwise reach the DOM or the render loop unbounded. */ -import { describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { MAX_COMPONENT_FANOUT, MAX_FLOW_MODULES, @@ -18,6 +18,7 @@ import { MAX_VALUE_NODES, MAX_RECORDING_NODES, MAX_VALUE_STRING_CHARS, + fetchRecording, isAppRecording, parseRecording } from './rawAppRecordingLoad' @@ -546,3 +547,14 @@ describe('parseRecording', () => { expect(kindOf(pipeline(sample(10, 20)))).toBe('pipeline') }) }) + +describe('fetchRecording', () => { + afterEach(() => vi.unstubAllGlobals()) + + it("never sends the visitor's cookies to the URL the link names", async () => { + const fetchMock = vi.fn(async () => new Response(JSON.stringify(valid()))) + vi.stubGlobal('fetch', fetchMock) + await expect(fetchRecording('/api/w/demo/some/path')).resolves.toEqual(valid()) + expect(fetchMock).toHaveBeenCalledWith('/api/w/demo/some/path', { credentials: 'omit' }) + }) +}) diff --git a/frontend/src/lib/components/recording/rawAppRecordingLoad.ts b/frontend/src/lib/components/recording/rawAppRecordingLoad.ts index b52cbd4ccb..c5289ded80 100644 --- a/frontend/src/lib/components/recording/rawAppRecordingLoad.ts +++ b/frontend/src/lib/components/recording/rawAppRecordingLoad.ts @@ -609,7 +609,9 @@ export async function fetchRecording( url: string, onProgress?: (loaded: number, total: number) => void ): Promise<unknown> { - const res = await fetch(url) + // `url` comes from the page's `?src=`, so anyone who can send a link picks it. + // Fetched with the visitor's cookies, a same-origin API URL would run as them. + const res = await fetch(url, { credentials: 'omit' }) if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`) const total = Number(res.headers.get('content-length')) || 0 if (total > MAX_RECORDING_BYTES) throw new Error(`Recording is too large (${total} bytes)`) diff --git a/frontend/src/lib/components/resourceConnectionTest.ts b/frontend/src/lib/components/resourceConnectionTest.ts index 332ebaf776..161ee6c503 100644 --- a/frontend/src/lib/components/resourceConnectionTest.ts +++ b/frontend/src/lib/components/resourceConnectionTest.ts @@ -126,7 +126,9 @@ async function mintApiToken(resourceType: string): Promise<string> { requestBody: { label: `ephemeral-test-connection: ${resourceType}`, expiration: new Date(Date.now() + API_TOKEN_TTL_MS).toISOString(), - scopes: ['settings:write'] + scopes: ['settings:write'], + // The test endpoint lets a superadmin reach private endpoints; the scope bounds the rest. + super_admin: true } }) } diff --git a/frontend/src/lib/components/resources/ResourcesList.svelte b/frontend/src/lib/components/resources/ResourcesList.svelte index 92654d43f5..0b4c8b5325 100644 --- a/frontend/src/lib/components/resources/ResourcesList.svelte +++ b/frontend/src/lib/components/resources/ResourcesList.svelte @@ -2,6 +2,10 @@ import { getLocalDraftHint } from '$lib/localDraftHints.svelte' import { page } from '$app/state' import oauthConnectRegistry from '$oauth_connect_registry' + import { + NATIVE_TRIGGER_SERVICES, + serviceForResourceType + } from '$lib/components/triggers/native/utils' import { isNewTabClick } from '$lib/navigation' import AppConnect from '$lib/components/AppConnectDrawer.svelte' import CenteredPage from '$lib/components/CenteredPage.svelte' @@ -69,6 +73,7 @@ Link, Palette, Pen, + Plug, Plus, RotateCw, Save, @@ -205,6 +210,7 @@ let appConnect: AppConnect | undefined = $state(undefined) let supabaseConnect: SupabaseConnect | undefined = $state(undefined) let deleteConfirmedCallback: (() => void) | undefined = $state(undefined) + let reconnectConfirm: { path: string; reconnect: () => void } | undefined = $state(undefined) let deleteIsLinked = $state(false) let deletePath = $state('') let loading = $state({ @@ -888,6 +894,26 @@ </div> </ConfirmationModal> +<ConfirmationModal + open={Boolean(reconnectConfirm)} + title="Reconnect resource" + confirmationText="Reconnect" + type="reload" + on:canceled={() => { + reconnectConfirm = undefined + }} + on:confirmed={() => { + reconnectConfirm?.reconnect() + reconnectConfirm = undefined + }} +> + <span> + Once reconnected, every script, flow and trigger using + <span class="font-semibold break-all">{reconnectConfirm?.path}</span> acts as the account you sign + in with. + </span> +</ConfirmationModal> + <DeployWorkspaceDrawer bind:this={deploymentDrawer} /> <Drawer bind:this={inferrer} size="800px"> @@ -1280,7 +1306,7 @@ </Head> <tbody class="divide-y bg-surface"> {#if filteredItems} - {#each filteredItems as { path, description, resource_type, extra_perms, workspace_id, is_oauth, is_linked, account, refresh_error, is_expired, grant_type, scopes, marked, is_refreshed, labels, inherited_labels, ws_specific, draft_only, is_draft }} + {#each filteredItems as { path, description, resource_type, extra_perms, workspace_id, is_oauth, is_linked, account, refresh_error, is_expired, grant_type, scopes, client, is_workspace_integration, marked, is_refreshed, labels, inherited_labels, ws_specific, draft_only, is_draft }} {@const hasDraft = getLocalDraftHint($operatingWorkspace, 'resource', path) ?? is_draft} {@const canWrite = @@ -1397,7 +1423,11 @@ <div> Latest exchange of the refresh token did not succeed. Error: {refresh_error} </div> - {@render oauthIdentity(resource_type, grant_type)} + {@render oauthIdentity( + resource_type, + grant_type, + is_workspace_integration + )} {@render oauthScopes(resource_type, scopes)} {/snippet} </Popover> @@ -1414,7 +1444,11 @@ this variable is fetched or you can request is to be refreshed in the dropdown on the right. </div> - {@render oauthIdentity(resource_type, grant_type)} + {@render oauthIdentity( + resource_type, + grant_type, + is_workspace_integration + )} {@render oauthScopes(resource_type, scopes)} {/snippet} </Popover> @@ -1429,7 +1463,11 @@ The resource was connected through OAuth and the token is not expired. </div> - {@render oauthIdentity(resource_type, grant_type)} + {@render oauthIdentity( + resource_type, + grant_type, + is_workspace_integration + )} {@render oauthScopes(resource_type, scopes)} {/snippet} </Popover> @@ -1519,6 +1557,34 @@ } } }, + ...(is_oauth + ? [ + { + displayName: 'Reconnect', + icon: Plug, + disabled: !canWrite || !showCreateButtons, + // A workspace app's account names its service, not a client. + action: () => { + const reconnect = () => + appConnect?.open?.( + client?.endsWith('_sandbox') ? client : resource_type, + path, + scopes ?? [], + is_workspace_integration ?? false + ) + // Everyone using a shared resource acts as whoever reconnects it. + if ( + path.startsWith('f/') || + Object.keys(extra_perms ?? {}).length > 0 + ) { + reconnectConfirm = { path, reconnect } + } else { + reconnect() + } + } + } + ] + : []), ...(account != undefined ? [ { @@ -1717,12 +1783,25 @@ <!-- Slack's bot and user tokens both come from the sign-in flow, so its grant does not say whose identity the token carries. --> -{#snippet oauthIdentity(resourceType: string, grantType: string | undefined)} +{#snippet oauthIdentity( + resourceType: string, + grantType: string | undefined, + viaWorkspaceApp: boolean | undefined +)} {#if grantType === 'client_credentials'} <div class="mt-2">Connected as an app, with client credentials.</div> {:else if !(oauthConnectRegistry as Record<string, any>)[resourceType]?.user_scopes} <div class="mt-2">Connected as the user who connected it, with authorization code.</div> {/if} + {@const service = viaWorkspaceApp ? serviceForResourceType(resourceType) : undefined} + {#if service} + <div class="mt-2"> + Connected through the workspace's own {NATIVE_TRIGGER_SERVICES[service].serviceDisplayName} app + (Workspace settings → Integration triggers). + </div> + {:else if grantType !== 'client_credentials'} + <div class="mt-2">Connected through the instance's OAuth client.</div> + {/if} {/snippet} {#snippet oauthScopes(resourceType: string, scopes: string[] | undefined)} diff --git a/frontend/src/lib/components/runs/FlowApprovalWaitingRow.svelte b/frontend/src/lib/components/runs/FlowApprovalWaitingRow.svelte new file mode 100644 index 0000000000..45cfe90734 --- /dev/null +++ b/frontend/src/lib/components/runs/FlowApprovalWaitingRow.svelte @@ -0,0 +1,136 @@ +<script lang="ts"> + import { resource } from 'runed' + import { ChevronDown, ExternalLink, Hourglass } from 'lucide-svelte' + import { Badge, Button } from '$lib/components/common' + import { JobService, type FlowModule, type Job } from '$lib/gen' + import FlowStatusWaitingForEvents from '../FlowStatusWaitingForEvents.svelte' + import StepIdBadge from '../flows/content/StepIdBadge.svelte' + import { displayDate } from '$lib/utils' + import Tooltip from '$lib/components/meltComponents/Tooltip.svelte' + + interface Props { + /** The run the step belongs to: the page's run, or a subflow, branch or loop run under it. */ + job: Job + module: FlowModule + isOwner: boolean + /** The step's id, chained after the subflow steps leading to it (`outer:r:s`). */ + chainedId: string + /** The page run's step the graph selects: the step itself, or the one holding its run. */ + graphStep: string + onSelectStep: () => void + } + + let { job, module, isOwner, chainedId, graphStep, onSelectStep }: Props = $props() + + // Primitives: each poll brings a new `job` object, which would refetch on every poll. + let workspace = $derived(job.workspace_id) + let jobId = $derived(job.id) + let stepId = $derived(module.id) + const detail = resource( + () => ({ workspace, jobId, stepId }), + async ({ workspace, jobId, stepId }) => + workspace ? JobService.getApprovalStepDetail({ workspace, jobId, stepId }) : undefined + ) + + // Open for whoever can act on it; a long description or form takes room only for them. + let toggled = $state<boolean | undefined>(undefined) + let expanded = $derived(toggled ?? detail.current?.can_approve ?? isOwner) + + // Worded as the approval page words it. Admins and flow owners can approve any step, so they + // are not listed. + function canApproveLabel(): string { + const ac = detail.current?.approval_conditions + const who = !ac?.user_auth_required + ? 'anyone with the approval link' + : ac.user_groups_required.length > 0 + ? `members of ${ac.user_groups_required.join(', ')}` + : 'any signed-in member' + return ac?.self_approval_disabled ? `${who} · self-approval disabled` : who + } + + const namesLabel = (names: string[]) => + names.slice(0, 2).join(', ') + (names.length > 2 ? ` +${names.length - 2}` : '') + + let toggleLabel = $derived(expanded ? 'Hide the approval form' : 'Show the approval form') +</script> + +<div class="flex items-start gap-3 px-4 py-2 border-t text-xs"> + <Hourglass size={14} class="shrink-0 mt-[3px] text-violet-500" /> + <div class="flex flex-1 min-w-0 flex-wrap items-center gap-x-3 gap-y-0.5"> + <span class="flex flex-wrap items-center gap-1 min-w-0 w-64 max-w-full -ml-2"> + <Button + variant="subtle" + unifiedSize="xs" + btnClasses="justify-start min-w-0 gap-1" + title="Show {graphStep} in the graph" + onclick={onSelectStep} + > + <span class="truncate">{module.summary || module.id}</span> + {#if module.summary || chainedId !== module.id} + <StepIdBadge id={chainedId} maxLength={24} /> + {/if} + </Button> + </span> + <span + class="flex flex-1 basis-48 flex-wrap items-center gap-x-3 gap-y-0.5 min-w-0 text-secondary" + > + {#if detail.current} + <span><span class="text-hint">Can approve:</span> {canApproveLabel()}</span> + {@const approvals = detail.current.approvals} + {#if approvals.length > 0} + <!-- Two names keep the row on one line; all of them, with times, are on hover. --> + <Tooltip small> + {#snippet text()} + {#each approvals as a} + <div> + {a.approver}{#if a.created_at}<span class="opacity-70" + >{` · ${displayDate(a.created_at)}`}</span + >{/if} + </div> + {/each} + {/snippet} + <span> + {approvals.length} of {detail.current.required_events} approvals: + <span class="text-primary">{namesLabel(approvals.map((a) => a.approver))}</span> + </span> + </Tooltip> + {/if} + {/if} + <!-- The page the Home list and links sent through other channels open, for this run. --> + <Button + variant="subtle" + unifiedSize="xs" + href="/approve/{workspace ?? ''}/{jobId}" + target="_blank" + endIcon={{ icon: ExternalLink }} + > + Approval page + </Button> + </span> + </div> + <span class="flex shrink-0 items-center gap-1"> + <Badge color="violet" small>Waiting</Badge> + <Button + variant="subtle" + unifiedSize="xs" + iconOnly + startIcon={{ icon: ChevronDown, classes: expanded ? 'rotate-180' : '' }} + title={toggleLabel} + aria-label={toggleLabel} + aria-expanded={expanded} + onclick={() => (toggled = !expanded)} + /> + </span> +</div> +{#if expanded} + <!-- The step's own approval panel, unchanged: its description, form and buttons. --> + <div class="px-4 pt-1 pb-3"> + <!-- A partial approval changes nothing the job's updates carry: refetch the count. --> + <FlowStatusWaitingForEvents + workspaceId={job.workspace_id} + {job} + {isOwner} + onAction={() => detail.refetch()} + /> + </div> +{/if} diff --git a/frontend/src/lib/components/runs/FlowApprovals.svelte b/frontend/src/lib/components/runs/FlowApprovals.svelte new file mode 100644 index 0000000000..698519a6a3 --- /dev/null +++ b/frontend/src/lib/components/runs/FlowApprovals.svelte @@ -0,0 +1,249 @@ +<script lang="ts"> + import { resource } from 'runed' + import { CircleCheck, CircleX, TimerOff } from 'lucide-svelte' + import { Badge, Button } from '$lib/components/common' + import { JobService, type FlowModule, type Job } from '$lib/gen' + import { displayDate, type StateStore } from '$lib/utils' + import FlowExecutionStatus from './FlowExecutionStatus.svelte' + import FlowApprovalWaitingRow from './FlowApprovalWaitingRow.svelte' + import { pendingAgentApproval } from '../agentRequest' + import StepIdBadge from '../flows/content/StepIdBadge.svelte' + + interface Props { + job: Job + isOwner: boolean + suspendStatus: StateStore<Record<string, { job: Job; nb: number; prefix?: string }>> + /** Selects the step in the run's graph. */ + onSelectStep: (stepId: string) => void + } + + let { job, isOwner, suspendStatus, onSelectStep }: Props = $props() + + type Approver = { approver: string; approved_at?: string; approved?: boolean } + /** `chainedId`: the step's id after the subflow steps leading to it (`outer:r:s`). + * `graphStep`: its first id. Step ids are unique across a flow, loop and branch steps + * included, so that one is a node of this run's graph. */ + type Located = { chainedId: string; graphStep: string } + type DoneRow = Located & { + key: string + stepId: string + summary?: string + approvers: Approver[] + /** `rejected` and `timedOut`: the flow continued past it (`continue_on_disapprove_timeout`). */ + outcome: Outcome + } + type Wait = Located & { job: Job; module: FlowModule } + + type Outcome = 'approved' | 'rejected' | 'timedOut' + // Entries written before `approved` was recorded are approvals. + const outcome = (approvers: Approver[], required: number | undefined): Outcome => + approvers.some((a) => a.approved === false) + ? 'rejected' + : approvers.length < (required ?? 1) + ? 'timedOut' + : 'approved' + + let ownDone = $derived.by((): DoneRow[] => { + const statuses = job.flow_status?.modules ?? [] + const flowStep = job.flow_status?.step ?? 0 + return (job.raw_flow?.modules ?? []).flatMap((module, i): DoneRow[] => { + const status = statuses[i] + const approvers = status?.approvers ?? [] + if (!module.suspend || status?.type !== 'Success' || status.skipped) return [] + // No response and the flow moved past the step after it: it timed out and continued. + // While it waits, `step` is that next step's index. + if (approvers.length === 0 && flowStep <= i + 1) return [] + return [ + { + key: module.id, + stepId: module.id, + chainedId: module.id, + graphStep: module.id, + summary: module.summary || undefined, + approvers, + outcome: outcome(approvers, module.suspend.required_events) + } + ] + }) + }) + + // Every approval the run waits on: its own step, or one in a run nested under it (a subflow, + // branch or loop run), which the run's graph shows inside the step holding it. + let waits = $derived.by((): Wait[] => { + const step = job.flow_status?.step ?? 0 + const own = + job.flow_status?.modules?.[step]?.type === 'WaitingForEvents' + ? job.raw_flow?.modules?.[step - 1] + : undefined + if (own?.suspend) return [{ job, module: own, chainedId: own.id, graphStep: own.id }] + return Object.values(suspendStatus.val ?? {}).flatMap(({ job: waiting, prefix }): Wait[] => { + const module = waiting.raw_flow?.modules?.[(waiting.flow_status?.step ?? 0) - 1] + if (waiting.id === job.id || !module?.suspend) return [] + // The prefix chains the subflow steps leading to the run, not loops or branches. + const chain = [...(prefix?.split(':').filter(Boolean) ?? []), module.id] + return [{ job: waiting, module, chainedId: chain.join(':'), graphStep: chain[0] }] + }) + }) + + // Mirrors `may_hold_approval` on the server: a subflow, or a loop or branch holding one. + function mayHoldApproval(m: FlowModule): boolean { + const holds = (modules: FlowModule[] | undefined) => + (modules ?? []).some((x) => !!x.suspend || mayHoldApproval(x)) + const v = m.value + switch (v.type) { + case 'flow': + return true + case 'forloopflow': + case 'whileloopflow': + return holds(v.modules) + case 'branchone': + return holds(v.default) || v.branches.some((b) => holds(b.modules)) + case 'branchall': + return v.branches.some((b) => holds(b.modules)) + default: + return false + } + } + + // Who approved a nested run's steps is kept on that run: read when the run has a step that + // can hold one, then again only when its waits change or it finishes, not at every step. + // Primitives: each poll brings a new `job` object, which would refetch on every poll. + let nests = $derived((job.raw_flow?.modules ?? []).some(mayHoldApproval)) + let workspace = $derived(job.workspace_id) + let jobId = $derived(job.id) + let moved = $derived(`${job.type}:${waits.map((w) => w.job.id + w.module.id)}`) + const nested = resource( + () => ({ nests, workspace, jobId, moved }), + async ({ nests, workspace, jobId }) => + nests && workspace ? JobService.listNestedApprovals({ workspace, jobId }) : undefined + ) + + // In the order they were decided: own and nested steps interleave in a flow's run. + const decidedAt = (r: DoneRow) => + r.approvers.reduce((t, a) => (a.approved_at && a.approved_at > t ? a.approved_at : t), '') + let done = $derived( + [ + ...ownDone, + ...(nested.current?.approvals ?? []).map( + (a): DoneRow => ({ + key: `${a.job_id}:${a.step_id}`, + stepId: a.step_id, + chainedId: [...a.subflows, a.step_id].join(':'), + graphStep: a.subflows[0] ?? a.step_id, + summary: a.step_summary, + approvers: a.approvers, + outcome: outcome(a.approvers, a.required_events) + }) + ) + ].sort((a, b) => decidedAt(a).localeCompare(decidedAt(b))) + ) + + // Waits the rows don't hold: an agent asking for a tool approval, or a run whose steps are not + // loaded. + let otherWaiting = $derived( + !!pendingAgentApproval(job) || + (waits.length === 0 && Object.keys(suspendStatus.val ?? {}).length > 0) + ) + + // Counts, not "N of M": a loop's step counts once per iteration, and the total is unknown + // until the loop ends. + let counts = $derived( + [ + [done.filter((r) => r.outcome == 'approved').length, 'approved'], + [done.filter((r) => r.outcome == 'rejected').length, 'rejected'], + [done.filter((r) => r.outcome == 'timedOut').length, 'timed out'], + [waits.length, 'waiting'] + ] + .filter(([n]) => n) + .map(([n, label]) => `${n} ${label}`) + .join(' · ') + ) + let stepCount = $derived(done.length + waits.length) +</script> + +{#if stepCount > 0 || otherWaiting} + <div class="rounded-md border bg-surface-tertiary"> + <div class="flex items-center justify-between px-4 py-2 text-xs font-semibold text-emphasis"> + <span>Approvals</span> + {#if stepCount > 0} + <span class="font-normal text-secondary">{counts}</span> + {/if} + </div> + {#each done as row (row.key)} + <div class="flex items-start gap-3 px-4 py-2 border-t text-xs"> + {#if row.outcome == 'rejected'} + <CircleX size={14} class="shrink-0 mt-[3px] text-red-500" /> + {:else if row.outcome == 'timedOut'} + <TimerOff size={14} class="shrink-0 mt-[3px] text-yellow-500" /> + {:else} + <CircleCheck size={14} class="shrink-0 mt-[3px] text-green-500" /> + {/if} + <div class="flex flex-1 min-w-0 flex-wrap items-center gap-x-3 gap-y-0.5"> + <span class="flex items-center gap-1 min-w-0 w-64 max-w-full -ml-2"> + <!-- Into the graph below, where the step's own status, logs and result are. --> + <Button + variant="subtle" + unifiedSize="xs" + btnClasses="justify-start min-w-0 gap-1" + title="Show {row.graphStep} in the graph" + onclick={() => onSelectStep(row.graphStep)} + > + <span class="truncate">{row.summary || row.stepId}</span> + {#if row.summary || row.chainedId !== row.stepId} + <StepIdBadge id={row.chainedId} maxLength={24} /> + {/if} + </Button> + </span> + <span + class="flex flex-1 basis-48 flex-wrap items-center gap-x-3 gap-y-0.5 min-w-0 text-secondary" + > + <!-- Unkeyed: the status stores resume ids truncated to 16 bits, so two can collide. --> + {#each row.approvers as approver} + <span> + <span class="text-primary">{approver.approver}</span> + {#if approver.approved_at} + <span class="text-hint">· {displayDate(approver.approved_at)}</span> + {/if} + </span> + {/each} + </span> + </div> + <span class="shrink-0"> + {#if row.outcome == 'rejected'} + <Badge color="red" small>Rejected, continued</Badge> + {:else if row.outcome == 'timedOut'} + <Badge color="yellow" small>Timed out, continued</Badge> + {:else} + <Badge color="green" small>Approved</Badge> + {/if} + </span> + </div> + {/each} + {#if nested.current?.more} + <p class="px-4 py-2 border-t text-xs text-hint"> + More approvals in nested runs than shown here: they are on those runs' own pages. + </p> + {/if} + {#each waits as wait (`${wait.job.id}:${wait.module.id}`)} + <FlowApprovalWaitingRow + job={wait.job} + module={wait.module} + chainedId={wait.chainedId} + graphStep={wait.graphStep} + {isOwner} + onSelectStep={() => onSelectStep(wait.graphStep)} + /> + {/each} + {#if otherWaiting} + <div class="px-4 pt-1 pb-3 border-t"> + <FlowExecutionStatus + {job} + {isOwner} + {suspendStatus} + innerModules={job.flow_status?.modules} + embedded + /> + </div> + {/if} + </div> +{/if} diff --git a/frontend/src/lib/components/runs/FlowExecutionStatus.svelte b/frontend/src/lib/components/runs/FlowExecutionStatus.svelte index d3bed5d562..38f6f4695c 100644 --- a/frontend/src/lib/components/runs/FlowExecutionStatus.svelte +++ b/frontend/src/lib/components/runs/FlowExecutionStatus.svelte @@ -11,9 +11,11 @@ isOwner: boolean innerModules: FlowStatusModule[] | undefined suspendStatus: StateStore<Record<string, { job: Job; nb: number }>> + /** Inside a card of its own (the run's approvals): no frame of its own. */ + embedded?: boolean } - let { job, isOwner, suspendStatus }: Props = $props() + let { job, isOwner, suspendStatus, embedded = false }: Props = $props() const isWaitingForEvents = $derived( job?.flow_status?.modules?.[job?.flow_status?.step]?.type === 'WaitingForEvents' @@ -27,7 +29,9 @@ {#if job && anyStatusActive} <div - class="rounded-md border shadow-md p-4 bg-surface-tertiary flex flex-col justify-center" + class="{embedded + ? '' + : 'rounded-md border shadow-md p-4 bg-surface-tertiary'} flex flex-col justify-center" transition:slide={{ duration: 150 }} > {#if isWaitingForEvents} diff --git a/frontend/src/lib/components/runs/JobDetailHeader.svelte b/frontend/src/lib/components/runs/JobDetailHeader.svelte index a2b19a54bf..75be13f4f5 100644 --- a/frontend/src/lib/components/runs/JobDetailHeader.svelte +++ b/frontend/src/lib/components/runs/JobDetailHeader.svelte @@ -52,6 +52,12 @@ displayPersistentScriptDefinition?: boolean openPersistentScriptDrawer?: () => void concurrencyKey?: string + /** When the job was first due, if its concurrency limit held it back. */ + concurrencyDeferredFrom?: string + /** When its concurrency limit let in the job it had held back. */ + concurrencyReleasedAt?: string + /** Why the step the flow is at has not started. */ + stepWaiting?: 'sleep' | 'concurrency' compact?: boolean extraCompact?: boolean onFilterByConcurrencyKey?: (key: string) => void @@ -67,6 +73,9 @@ displayPersistentScriptDefinition = false, openPersistentScriptDrawer, concurrencyKey, + concurrencyDeferredFrom, + concurrencyReleasedAt, + stepWaiting, compact = false, extraCompact = false, onFilterByConcurrencyKey, @@ -75,6 +84,8 @@ onResolutionChanged }: Props = $props() + let heldByConcurrency = $derived(!!concurrencyDeferredFrom && !concurrencyReleasedAt) + let togglingResolution = $state(false) let resolutionNote = $state('') @@ -386,7 +397,7 @@ <div class="flex flex-row flex-wrap justify-between items-center gap-x-4 py-2 px-3"> <div class="flex flex-row flex-wrap gap-2 items-center flex-1"> {#if job} - <JobStatus {job} /> + <JobStatus {job} {heldByConcurrency} {stepWaiting} /> <div class="flex items-baseline gap-1 text-xs"> <span class="text-secondary flex-shrink-0">Job ID</span> <span class="text-primary"> @@ -473,7 +484,7 @@ <div class="flex flex-wrap items-center gap-3 min-w-0 grow"> <!-- Status icon --> <div class="flex-shrink-0"> - <JobStatusIcon {job} roundedFull /> + <JobStatusIcon {job} roundedFull {heldByConcurrency} {stepWaiting} /> </div> <!-- Two-row section: title on top, badges on bottom --> @@ -511,13 +522,15 @@ <!-- Job Status --> <div class="flex items-baseline flex-wrap gap-x-2 gap-y-1"> - <JobStatus {job} /> + <JobStatus {job} {heldByConcurrency} {stepWaiting} /> <RunBadges {job} {displayPersistentScriptDefinition} {openPersistentScriptDrawer} {concurrencyKey} + {concurrencyDeferredFrom} + {concurrencyReleasedAt} {onFilterByConcurrencyKey} showScriptHash={showScriptHashInBadges} large={false} diff --git a/frontend/src/lib/components/runs/JobRunsPreview.svelte b/frontend/src/lib/components/runs/JobRunsPreview.svelte index 9c5144166e..cd764d0fe8 100644 --- a/frontend/src/lib/components/runs/JobRunsPreview.svelte +++ b/frontend/src/lib/components/runs/JobRunsPreview.svelte @@ -1,5 +1,6 @@ <script lang="ts"> - import { ConcurrencyGroupsService, type Job, type WorkflowStatus } from '../../gen' + import { type Job, type WorkflowStatus } from '../../gen' + import { useConcurrencyKeyStatus } from './useConcurrencyKeyStatus.svelte' import JobLoader from '../JobLoader.svelte' import DisplayResult from '../DisplayResult.svelte' import JobArgs from '../JobArgs.svelte' @@ -15,7 +16,7 @@ import FlowAssetsHandler, { initFlowGraphAssetsCtx } from '../flows/FlowAssetsHandler.svelte' import JobAssetsViewer from '../assets/JobAssetsViewer.svelte' import JobDetailHeader from './JobDetailHeader.svelte' - import FlowExecutionStatus from './FlowExecutionStatus.svelte' + import FlowApprovals from './FlowApprovals.svelte' interface Props { id: string @@ -34,12 +35,7 @@ let loadError: string | undefined = $state(undefined) let isLoadingJobDetails: boolean = $state(false) - let lastJobId: string | undefined = $state(undefined) - let concurrencyKey: string | undefined = $state(undefined) - async function getConcurrencyKey(job: Job) { - lastJobId = job.id - concurrencyKey = await ConcurrencyGroupsService.getConcurrencyKey({ id: job.id }) - } + const concurrency = useConcurrencyKeyStatus(() => job) let viewTab = $state('logs') @@ -99,10 +95,6 @@ } }) - $effect(() => { - job?.id && lastJobId !== job.id && untrack(() => job && getConcurrencyKey(job)) - }) - let jobLoader: JobLoader | undefined = $state(undefined) // Set all tabs content to the same height to prevent layout jumps @@ -121,6 +113,8 @@ // Flow execution status state let suspendStatus: StateStore<Record<string, { job: Job; nb: number }>> = $state({ val: {} }) let isOwner: boolean = $state(false) + let flowStatusViewer: FlowStatusViewer | undefined = $state(undefined) + let flowStatusEl: HTMLElement | undefined = $state(undefined) </script> <JobLoader @@ -151,7 +145,9 @@ <JobDetailHeader {job} compact - {concurrencyKey} + concurrencyKey={concurrency.key} + concurrencyDeferredFrom={concurrency.deferredFrom} + concurrencyReleasedAt={concurrency.releasedAt} onFilterByConcurrencyKey={handleFilterByConcurrencyKey} onFilterByWorker={handleFilterByWorker} {onResolutionChanged} @@ -172,11 +168,14 @@ {/if} <div class="w-full mt-2"> {#if isFlow} - <FlowExecutionStatus + <FlowApprovals {job} {isOwner} - innerModules={job?.flow_status?.modules} {suspendStatus} + onSelectStep={(stepId) => { + flowStatusViewer?.selectStep(stepId) + flowStatusEl?.scrollIntoView({ behavior: 'smooth', block: 'start' }) + }} /> {/if} </div> @@ -192,9 +191,10 @@ </div> <!-- Job execution content --> - <div class="w-full mt-6"> + <div class="w-full mt-6" bind:this={flowStatusEl}> {#if isFlow} <FlowStatusViewer + bind:this={flowStatusViewer} jobId={job.id} workspaceId={job.workspace_id} initialJob={job} diff --git a/frontend/src/lib/components/runs/JobStatusIcon.svelte b/frontend/src/lib/components/runs/JobStatusIcon.svelte index c37791310e..5434389fc9 100644 --- a/frontend/src/lib/components/runs/JobStatusIcon.svelte +++ b/frontend/src/lib/components/runs/JobStatusIcon.svelte @@ -6,12 +6,14 @@ Calendar, Check, FastForward, + Gauge, Hourglass, - Play, + Moon, ShieldQuestion, Wrench, X } from 'lucide-svelte' + import RunningStatusIcon from './RunningStatusIcon.svelte' import type { Job } from '$lib/gen' import { isSuspended } from '../agentRequest' @@ -19,9 +21,19 @@ job: Job isExternal?: boolean roundedFull?: boolean + /** Its concurrency limit holds the job back. */ + heldByConcurrency?: boolean + /** Why the step the flow is at has not started. */ + stepWaiting?: 'sleep' | 'concurrency' } - let { job, isExternal = false, roundedFull = false }: Props = $props() + let { + job, + isExternal = false, + roundedFull = false, + heldByConcurrency = false, + stepWaiting + }: Props = $props() </script> <div class="flex items-center justify-start"> @@ -65,9 +77,31 @@ <Badge color="violet" {roundedFull} baseClass={roundedFull ? '' : '!px-1.5'} title="Suspended"> <Hourglass size={14} /> </Badge> + {:else if 'running' in job && job.running && stepWaiting === 'sleep'} + <Badge {roundedFull} baseClass={roundedFull ? '' : '!px-1.5'} title="Sleeping"> + <Moon size={14} /> + </Badge> + {:else if 'running' in job && job.running && stepWaiting === 'concurrency'} + <Badge + color="orange" + {roundedFull} + baseClass={roundedFull ? '' : '!px-1.5'} + title="Step held by concurrency limit" + > + <Gauge size={14} /> + </Badge> {:else if 'running' in job && job.running} <Badge color="yellow" {roundedFull} baseClass={roundedFull ? '' : '!px-1.5'}> - <Play size={14} /> + <RunningStatusIcon /> + </Badge> + {:else if 'running' in job && heldByConcurrency} + <Badge + color="orange" + {roundedFull} + baseClass={roundedFull ? '' : '!px-1.5'} + title="Held by concurrency limit" + > + <Gauge size={14} /> </Badge> {:else if job && 'running' in job && job.scheduled_for && forLater(job.scheduled_for)} <Badge color="blue" {roundedFull} baseClass={roundedFull ? '' : '!px-1.5'}> diff --git a/frontend/src/lib/components/runs/RunBadges.svelte b/frontend/src/lib/components/runs/RunBadges.svelte index 2c31ed852c..90f807858b 100644 --- a/frontend/src/lib/components/runs/RunBadges.svelte +++ b/frontend/src/lib/components/runs/RunBadges.svelte @@ -1,11 +1,11 @@ <script lang="ts"> import Tooltip from '$lib/components/meltComponents/Tooltip.svelte' import PreprocessedArgsDisplay from '$lib/components/runs/PreprocessedArgsDisplay.svelte' - import { getJobKindDisplayLabel, truncateHash } from '$lib/utils' + import { getJobKindDisplayLabel, msToCompactDuration, truncateHash } from '$lib/utils' import { truncateRev } from '$lib/utils' import Badge from '$lib/components/common/badge/Badge.svelte' import Button from '$lib/components/common/button/Button.svelte' - import { ListFilter, Tag } from 'lucide-svelte' + import { AlertTriangle, ListFilter, Tag } from 'lucide-svelte' import type { Job } from '$lib/gen' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' import { userWorkspaces } from '$lib/stores' @@ -24,6 +24,10 @@ displayPersistentScriptDefinition?: boolean openPersistentScriptDrawer?: () => void concurrencyKey?: string + /** When the job was first due, if its concurrency limit held it back. */ + concurrencyDeferredFrom?: string + /** When its concurrency limit let in the job it had held back. */ + concurrencyReleasedAt?: string showScriptHash?: boolean onFilterByConcurrencyKey?: (key: string) => void large?: boolean @@ -34,10 +38,52 @@ displayPersistentScriptDefinition, openPersistentScriptDrawer, concurrencyKey, + concurrencyDeferredFrom, + concurrencyReleasedAt, showScriptHash = true, onFilterByConcurrencyKey, large = false }: Props = $props() + + // From when the limit first held the job to when it let it in, counting live while it holds + // it; the rest until it started is queue time. A job let in before the end of the hold was + // recorded shows nothing. + // A job canceled while held completes without ever being let in: it is not held any more. + let heldNow = $derived( + job.type === 'QueuedJob' && + !!concurrencyDeferredFrom && + !concurrencyReleasedAt && + !job.started_at + ) + let now = $state(Date.now()) + $effect(() => { + if (!heldNow) return + const id = setInterval(() => (now = Date.now()), 1000) + return () => clearInterval(id) + }) + let heldMs = $derived( + concurrencyDeferredFrom && (concurrencyReleasedAt || heldNow) + ? (concurrencyReleasedAt ? new Date(concurrencyReleasedAt).getTime() : now) - + new Date(concurrencyDeferredFrom).getTime() + : undefined + ) + let queuedAfterMs = $derived( + concurrencyReleasedAt && job.started_at + ? Math.max(new Date(job.started_at).getTime() - new Date(concurrencyReleasedAt).getTime(), 0) + : undefined + ) + // The steps of the wait-time warning on the status badge. + let heldColor = $derived( + heldMs == undefined + ? '' + : heldMs > 300_000 + ? 'text-red-500' + : heldMs > 30_000 + ? 'text-orange-500' + : heldMs > 5_000 + ? 'text-yellow-500' + : 'text-gray-400' + ) </script> {#if job.script_hash && showScriptHash && job.job_kind !== 'aiagent'} @@ -110,10 +156,23 @@ </div> {/each} {/if} +{#snippet held()} + {#if heldMs != undefined && heldMs > 0} + <span class="ml-1 inline-flex items-center gap-0.5 {heldColor}"> + <AlertTriangle size={10} />{msToCompactDuration(heldMs, 0)} + </span> + {/if} +{/snippet} + {#if concurrencyKey} <div> <Tooltip> {#snippet text()} + {#if heldMs != undefined} + Held by its concurrency limit for {msToCompactDuration(heldMs, 0)}{queuedAfterMs + ? `, then queued ${msToCompactDuration(queuedAfterMs, 0)}` + : ''}. + {/if} This job has concurrency limits enabled with the key: {#if onFilterByConcurrencyKey} <Button @@ -133,11 +192,11 @@ {/snippet} {#if onFilterByConcurrencyKey} <button onclick={() => onFilterByConcurrencyKey?.(concurrencyKey)}> - <Badge {large}>Concurrency: {truncateRev(concurrencyKey, 20)}</Badge> + <Badge {large}>Concurrency: {truncateRev(concurrencyKey, 20)}{@render held()}</Badge> </button> {:else} <a href={`/runs/?job_kinds=all&graph=ConcurrencyChart&concurrency_key=${concurrencyKey}`}> - <Badge {large}>Concurrency: {truncateRev(concurrencyKey, 20)}</Badge> + <Badge {large}>Concurrency: {truncateRev(concurrencyKey, 20)}{@render held()}</Badge> </a> {/if} </Tooltip> diff --git a/frontend/src/lib/components/runs/RunDetail.svelte b/frontend/src/lib/components/runs/RunDetail.svelte index b605704093..0e381047a1 100644 --- a/frontend/src/lib/components/runs/RunDetail.svelte +++ b/frontend/src/lib/components/runs/RunDetail.svelte @@ -6,7 +6,6 @@ type Script, type WorkflowStatus, type NewScript, - ConcurrencyGroupsService, MetricsService, WorkerService, type ScriptArgs @@ -74,8 +73,9 @@ import PageHeaderContent from '$lib/components/PageHeaderContent.svelte' import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte' import JobDetailHeader from '$lib/components/runs/JobDetailHeader.svelte' + import { useConcurrencyKeyStatus } from '$lib/components/runs/useConcurrencyKeyStatus.svelte' import ScriptRetryChain from '$lib/components/runs/ScriptRetryChain.svelte' - import FlowExecutionStatus from '$lib/components/runs/FlowExecutionStatus.svelte' + import FlowApprovals from '$lib/components/runs/FlowApprovals.svelte' import JobArgs from '$lib/components/JobArgs.svelte' import FlowProgressBar from '$lib/components/flows/FlowProgressBar.svelte' import JobProgressBar from '$lib/components/jobs/JobProgressBar.svelte' @@ -202,6 +202,8 @@ let viewTab: 'logs' | 'code' | 'stats' | 'assets' | 'traces' = $state('logs') let selectedJobStep: string | undefined = $state(undefined) + let graphEl: HTMLElement | undefined = $state(undefined) + let flowStatusViewer: FlowStatusViewer | undefined = $state(undefined) // Mirror of the graph's per-module display state (selected iteration of each // ForLoop, etc.). Drives both the iteration pre-fill and the iteration-count @@ -268,20 +270,13 @@ (localStorage.getItem('hideExplicitProgressTip') ?? 'false') == 'false' ) - let lastJobId: string | undefined = $state(undefined) - let concurrencyKey: string | undefined = $state(undefined) + const concurrency = useConcurrencyKeyStatus(() => job) setContext( 'FlowGraphAssetContext', initFlowGraphAssetsCtx({ getModules: () => job?.raw_flow?.modules ?? [] }) ) - async function getConcurrencyKey(job: Job | undefined) { - if (!job) return - lastJobId = job.id - concurrencyKey = await ConcurrencyGroupsService.getConcurrencyKey({ id: job.id }) - } - // Share read link: if the URL carries a `view_token`, install it so every job // read on this page (incl. flow steps, args, logs, SSE) is authorized by it. // Set eagerly at init (before JobLoader mounts and fires its first fetch), and @@ -708,9 +703,6 @@ return openEditInFork(kind, itemPath, workspaceId) } - $effect(() => { - job?.id && lastJobId !== job.id && untrack(() => getConcurrencyKey(job)) - }) $effect(() => { workspaceId && runId && untrack(() => onRunsPageChange()) }) @@ -1430,7 +1422,14 @@ openPersistentScriptDrawer={() => { persistentScriptDrawer?.open?.(persistentScriptDefinition) }} - {concurrencyKey} + concurrencyKey={concurrency.key} + concurrencyDeferredFrom={concurrency.deferredFrom} + concurrencyReleasedAt={concurrency.releasedAt} + stepWaiting={job.type === 'QueuedJob' + ? Object.values(graphModuleStates).find( + (s) => s.type === 'WaitingForExecutor' && s.waiting_reason + )?.waiting_reason + : undefined} /> {/if} </div> @@ -1453,6 +1452,8 @@ textPosition="bottom" slim showStepId + stepStates={graphModuleStates} + waitingNested={Object.keys(suspendStatus?.val ?? {}).length > 0} > {#snippet errorAction()} <!-- A saved agent's run is its one step: naming it adds nothing. --> @@ -1466,12 +1467,15 @@ {/if} {/snippet} </FlowProgressBar> - {#if suspendStatus} - <FlowExecutionStatus + {#if suspendStatus && job} + <FlowApprovals {job} {isOwner} {suspendStatus} - innerModules={job?.flow_status?.modules} + onSelectStep={(stepId) => { + flowStatusViewer?.selectStep(stepId) + graphEl?.scrollIntoView({ behavior: 'smooth', block: 'start' }) + }} /> {/if} </div> @@ -1650,9 +1654,10 @@ {:else if !job?.['deleted']} <div class="mt-10"></div> - <div class="w-full mt-10"> + <div class="w-full mt-10" bind:this={graphEl}> {#if job?.id} <FlowStatusViewer + bind:this={flowStatusViewer} jobId={job?.id ?? ''} onJobsLoaded={({ job: newJob }) => { job = newJob diff --git a/frontend/src/lib/components/runs/RunningStatusIcon.svelte b/frontend/src/lib/components/runs/RunningStatusIcon.svelte new file mode 100644 index 0000000000..f734f62706 --- /dev/null +++ b/frontend/src/lib/components/runs/RunningStatusIcon.svelte @@ -0,0 +1,13 @@ +<script lang="ts"> + import { CirclePlay } from 'lucide-svelte' + + interface Props { + size?: number + } + + let { size = 14 }: Props = $props() +</script> + +<!-- A running job: only the circle fades, so the play triangle stays legible. A spinner here would + read as "still loading", which is what it means everywhere else in the app. --> +<CirclePlay {size} class="motion-safe:[&_circle]:animate-ring-fade" /> diff --git a/frontend/src/lib/components/runs/useConcurrencyKeyStatus.svelte.ts b/frontend/src/lib/components/runs/useConcurrencyKeyStatus.svelte.ts new file mode 100644 index 0000000000..42b7f0224f --- /dev/null +++ b/frontend/src/lib/components/runs/useConcurrencyKeyStatus.svelte.ts @@ -0,0 +1,67 @@ +import { ConcurrencyGroupsService, type Job } from '$lib/gen' +import { getDbClockNow } from '$lib/forLater' + +/** A job's concurrency key and, if its limit held it back, when it was first due and when it was + * let in. */ +export function useConcurrencyKeyStatus(getJob: () => Job | undefined) { + type Status = { key: string; deferred_from?: string | null; released_at?: string | null } | null + let loaded = $state<{ jobId: string; status: Status } | undefined>(undefined) + + let id = $derived(getJob()?.id) + let phase = $derived.by(() => { + const job = getJob() + return job?.type === 'CompletedJob' ? 'done' : job?.['running'] ? 'running' : 'waiting' + }) + let scheduledFor = $derived(getJob()?.['scheduled_for'] as string | undefined) + + // Live updates do not carry a job's due time, so a limit holding it back is only seen by + // asking: once per phase (waiting, running, done), and every 5s while it waits once due. + $effect(() => { + const jobId = id + const waiting = phase === 'waiting' + const dueIn = scheduledFor ? new Date(scheduledFor).getTime() - getDbClockNow().getTime() : 0 + if (!jobId) return + let current = true + let stopped = false + let timer: ReturnType<typeof setTimeout> | undefined = undefined + const stop = () => { + stopped = true + clearTimeout(timer) + } + const load = () => + ConcurrencyGroupsService.getConcurrencyKeyStatus({ id: jobId }) + .then((status) => { + if (!current) return + loaded = { jobId, status } + // The key is written as the job is queued: none means it has no limit. + if (!status) stop() + }) + .catch(stop) + const poll = () => { + if (stopped) return + load() + timer = setTimeout(poll, 5000) + } + load() + // setTimeout fires at once past 2^31 - 1 ms. + if (waiting) timer = setTimeout(poll, Math.min(Math.max(dueIn, 5000), 2 ** 31 - 1)) + return () => { + current = false + stop() + } + }) + + let status = $derived(loaded?.jobId === id ? loaded?.status : undefined) + + return { + get key() { + return status?.key + }, + get deferredFrom() { + return status?.deferred_from ?? undefined + }, + get releasedAt() { + return status?.released_at ?? undefined + } + } +} diff --git a/frontend/src/lib/components/s3TableOps.test.ts b/frontend/src/lib/components/s3TableOps.test.ts index f32ce47c56..95a1cbb9db 100644 --- a/frontend/src/lib/components/s3TableOps.test.ts +++ b/frontend/src/lib/components/s3TableOps.test.ts @@ -14,6 +14,10 @@ describe('serverTableFormat', () => { expect(serverTableFormat('a.json')).toBeUndefined() expect(serverTableFormat('a.txt')).toBeUndefined() }) + + it('leaves an upper-case parquet extension to the download card', () => { + expect(serverTableFormat('a.PARQUET')).toBeUndefined() + }) }) describe('datatypeOf', () => { diff --git a/frontend/src/lib/components/s3TableOps.ts b/frontend/src/lib/components/s3TableOps.ts index f5d7bd758b..e82f2eddd0 100644 --- a/frontend/src/lib/components/s3TableOps.ts +++ b/frontend/src/lib/components/s3TableOps.ts @@ -1,13 +1,13 @@ -import { HelpersService, OpenAPI } from '$lib/gen' +import { AppService, HelpersService, OpenAPI } from '$lib/gen' import { getHeaders } from '$lib/gen/core/request' import { ColumnIdentity, type ColumnDef } from './apps/components/display/dbtable/utils' import type { IDbTableOps } from './dbOps' /** Files the server can page through as a table, without reading them whole. */ export function serverTableFormat(fileKey: string): 'parquet' | 'csv' | undefined { - const key = fileKey.toLowerCase() - if (key.endsWith('.parquet')) return 'parquet' - if (/\.(csv|tsv|jsonl|ndjson)$/.test(key)) return 'csv' + // The parquet reader requires the lower-case extension; the CSV reader takes any case. + if (fileKey.endsWith('.parquet')) return 'parquet' + if (/\.(csv|tsv|jsonl|ndjson)$/i.test(fileKey)) return 'csv' return undefined } @@ -18,6 +18,8 @@ export type S3TableSource = { s3ResourcePath?: string csvSeparator?: string csvHasHeader?: boolean + /** Read through a deployed app's `apps_u/*` routes. */ + app?: { path: string; presigned?: string } } type Chunk = { @@ -47,14 +49,29 @@ export async function s3TableOps( ): Promise<{ ops: IDbTableOps; csvSeparator?: string }> { const format = serverTableFormat(source.fileKey) if (!format) throw new Error(`${source.fileKey} cannot be read as a table`) + const app = source.app const common = { workspace: source.workspace, path: source.fileKey, storage: source.storage, s3ResourcePath: source.s3ResourcePath } + const signed = new URLSearchParams(app?.presigned ?? '') + const appCommon = app && { + workspace: source.workspace, + path: app.path, + fileKey: source.fileKey, + storage: source.storage, + sig: signed.get('sig') ?? undefined, + exp: signed.get('exp') ?? undefined + } const csvOptions: { csvSeparator?: string; csvHasHeader?: boolean } = - format === 'csv' ? { csvSeparator: source.csvSeparator, csvHasHeader: source.csvHasHeader } : {} + format === 'csv' + ? { + csvSeparator: source.csvSeparator, + csvHasHeader: source.csvHasHeader + } + : {} const filtersParam = (columnFilters: Record<string, unknown> | undefined) => columnFilters && Object.keys(columnFilters).length ? JSON.stringify(columnFilters) : undefined const searchParam = (quicksearch: string) => quicksearch.trim() || undefined @@ -67,8 +84,7 @@ export async function s3TableOps( orderBy?: string isDesc?: boolean }): Promise<Chunk> { - const data = { - ...common, + const args = { ...csvOptions, offset: params.offset, limit: params.limit, @@ -77,6 +93,13 @@ export async function s3TableOps( sortCol: params.orderBy, sortDesc: params.isDesc } + if (appCommon) { + const appData = { ...appCommon, ...args } + return (await (format === 'parquet' + ? AppService.appLoadParquetPreview(appData) + : AppService.appLoadCsvPreview(appData))) as Chunk + } + const data = { ...common, ...args } return (await (format === 'parquet' ? HelpersService.loadParquetPreview(data) : HelpersService.loadCsvPreview(data))) as Chunk @@ -89,7 +112,7 @@ export async function s3TableOps( field, datatype: datatypeOf(head.column_types?.[i]), // The server cannot read a struct, map or union as text to filter it. - filterable: !/^(Struct|Map|Union)/.test(head.column_types?.[i] ?? ""), + filterable: !/^(Struct|Map|Union)/.test(head.column_types?.[i] ?? ''), defaultvalue: '', isprimarykey: false, isidentity: ColumnIdentity.No, @@ -99,15 +122,18 @@ export async function s3TableOps( const ops: IDbTableOps = { dbType: 'duckdb', - tableKey: source.fileKey.split('/').pop() ?? source.fileKey, + // Named after the file without its extension: the table's CSV export appends `.csv`. + tableKey: (source.fileKey.split('/').pop() ?? source.fileKey).replace(/\.[^.]+$/, ''), colDefs, getCount: async ({ quicksearch, columnFilters }) => { - const res = await HelpersService.loadTableRowCount({ - ...common, + const args = { ...csvOptions, searchTerm: searchParam(quicksearch), filters: filtersParam(columnFilters) - }) + } + const res = appCommon + ? await AppService.appLoadTableCount({ ...appCommon, ...args }) + : await HelpersService.loadTableRowCount({ ...common, ...args }) return res.count ?? 0 }, getRows: async ({ diff --git a/frontend/src/lib/components/sessions/ImagePreviewSlot.svelte b/frontend/src/lib/components/sessions/ImagePreviewSlot.svelte new file mode 100644 index 0000000000..a63c853972 --- /dev/null +++ b/frontend/src/lib/components/sessions/ImagePreviewSlot.svelte @@ -0,0 +1,149 @@ +<script lang="ts"> + import { Button } from '$lib/components/common' + import ImagePanelViewer from '$lib/components/common/image/ImagePanelViewer.svelte' + import type { AIChatManager } from '../copilot/chat/AIChatManager.svelte' + import { asImageBlob, imageContentKey } from '../copilot/chat/files/imageFiles' + import type { ImageSource } from './previewRouter' + import { resource } from 'runed' + import { onDestroy } from 'svelte' + import { JobService } from '$lib/gen' + + interface Props { + manager: AIChatManager + source: ImageSource + label: string + } + + let { manager, source, label }: Props = $props() + + // A session link, never a message attachment: those share the namespace only by name. + const file = $derived( + source.kind === 'file' + ? manager.attachedFiles.files.find( + (f) => f.name === source.name && !f.messageScoped && !f.isFolderRoot + ) + : undefined + ) + // A folder whose permission lapsed after a reload keeps only its placeholder row. + const folderLocked = $derived( + source.kind === 'file' && + !file && + manager.attachedFiles.folders.some( + (f) => f.status === 'locked' && source.name.startsWith(`${f.name}/`) + ) + ) + + const messageImage = $derived.by(() => { + if (source.kind !== 'message') return undefined + // A user's attachment, or an image a tool produced (a screenshot). + for (const m of manager.displayMessages) { + if (m.role === 'user') { + for (const image of m.images ?? []) { + if (imageContentKey(image.dataUrl, image) === source.hash) return image + } + } else if (m.role === 'tool' && m.imageUrl?.startsWith('data:')) { + if (imageContentKey(m.imageUrl, m) === source.hash) + return { dataUrl: m.imageUrl, name: undefined } + } + } + return undefined + }) + + const blob = $derived( + file && file.status === 'ready' + ? asImageBlob(file.file, file.sourceName ?? file.name) + : undefined + ) + + // A live object URL keeps its blob's backing data (an unlinked file's IndexedDB copy + // included) until revoked, so each one is released when the next replaces it and on unmount. + let lastUrl: string | undefined + const blobUrl = $derived.by(() => { + if (lastUrl) URL.revokeObjectURL(lastUrl) + lastUrl = blob ? URL.createObjectURL(blob) : undefined + return lastUrl + }) + onDestroy(() => { + if (lastUrl) URL.revokeObjectURL(lastUrl) + }) + + // An inline result is fetched again from its job: the tab keeps only the job's address. + const resultImage = resource( + () => (source.kind === 'result' ? source : undefined), + async (s) => { + if (!s) return undefined + const full: unknown = s.nodeId + ? await JobService.resultById({ + workspace: s.workspace, + flowJobId: s.jobId, + nodeId: s.nodeId + }) + : await JobService.getCompletedJobResult({ workspace: s.workspace, id: s.jobId }) + let result = full + for (const key of s.path ?? []) result = (result as Record<string | number, unknown>)?.[key] + // DisplayResult takes either the base64 string or `{ content }`. + const value = (result as Record<string, unknown> | undefined)?.[s.format] + const b64 = + typeof value === 'string' + ? value + : typeof (value as { content?: unknown })?.content === 'string' + ? (value as { content: string }).content + : undefined + return b64 ? `data:image/${s.format};base64,${b64}` : null + } + ) + + const src = $derived( + source.kind === 'message' + ? messageImage?.dataUrl + : source.kind === 'result' + ? (resultImage.current ?? undefined) + : source.kind === 'url' + ? source.url + : blobUrl + ) + const name = $derived( + source.kind === 'file' + ? source.name.split('/').pop() || source.name + : source.kind === 'message' + ? messageImage?.name || label || 'Image' + : source.kind === 'result' + ? `${label || 'result'}.${source.format === 'jpeg' ? 'jpg' : source.format}` + : label || 'Image' + ) +</script> + +{#if src} + <ImagePanelViewer {src} {name} bytes={file?.size} /> +{:else if folderLocked} + <div class="flex flex-col items-start gap-2 p-4 text-xs text-secondary"> + <span>Your browser needs permission again to read this folder.</span> + <Button + unifiedSize="sm" + variant="default" + onClick={() => void manager.attachedFiles.regrantLocked()} + > + Restore access + </Button> + </div> +{:else if source.kind === 'result'} + <div class="p-4 text-xs text-secondary"> + {resultImage.loading + ? 'Loading the result…' + : resultImage.error + ? 'The result of this run could not be loaded.' + : 'This run’s result no longer holds an image.'} + </div> +{:else if file && file.status !== 'ready'} + <div class="p-4 text-xs text-secondary"> + {file.status === 'indexing' ? 'Loading…' : 'This image is no longer available.'} + </div> +{:else} + <div class="p-4 text-xs text-secondary"> + {source.kind === 'file' + ? 'This image is no longer linked to the session.' + : source.kind === 'message' + ? 'This image is not in the current chat.' + : 'This image could not be loaded.'} + </div> +{/if} diff --git a/frontend/src/lib/components/sessions/PreviewTabHost.svelte b/frontend/src/lib/components/sessions/PreviewTabHost.svelte index a69966caf9..ea561de25d 100644 --- a/frontend/src/lib/components/sessions/PreviewTabHost.svelte +++ b/frontend/src/lib/components/sessions/PreviewTabHost.svelte @@ -15,6 +15,7 @@ resolvePreviewTab, parsePreviewItemRoute, parsePreviewSelectedId, + parseImageRoute, showsView } from './previewRouter' import { withMenuHidden } from './sessionMode.svelte' @@ -22,7 +23,9 @@ import ArtifactViewer from '../copilot/chat/artifacts/ArtifactViewer.svelte' import RunFormPreviewSlot from './RunFormPreviewSlot.svelte' import S3FilePreview from '../S3FilePreview.svelte' + import ImagePreviewSlot from './ImagePreviewSlot.svelte' import { setOverlayHost } from '../common/overlayHost.svelte' + import { setImageOpener } from '../common/image/imageOpener' import { setReadOnlyWorkspace } from '../operatingWorkspace.svelte' let { @@ -83,6 +86,8 @@ () => runtime?.manager ) setReadOnlyWorkspace((ws) => !!ws && ws === workspaceId && permissions.readOnly) + // An image inside a tab (a run's result, a test result in an editor) opens in a tab beside it. + setImageOpener((source, label) => runtime?.manager.openImage?.(source, label)) // Every route into an editor ends here, the breadcrumb and the chat's openers included, so // this is where an editor the user cannot save is turned into the deployed page. const mode = $derived( @@ -519,6 +524,20 @@ showMetadata /> </div> +{:else if slot.kind === 'image' && mounted} + <div + class="absolute inset-0 flex flex-col min-h-0 bg-surface {visibility}" + aria-hidden={!active} + {inert} + > + {#if runtime} + <ImagePreviewSlot + manager={runtime.manager} + source={slot.source} + label={parseImageRoute(tab.url)?.label ?? ''} + /> + {/if} + </div> {:else if slot.kind === 'runform' && mounted} <div bind:this={overlayHostEl} diff --git a/frontend/src/lib/components/sessions/RawAppEditorView.svelte b/frontend/src/lib/components/sessions/RawAppEditorView.svelte index 9f5c606214..22114de11e 100644 --- a/frontend/src/lib/components/sessions/RawAppEditorView.svelte +++ b/frontend/src/lib/components/sessions/RawAppEditorView.svelte @@ -317,32 +317,17 @@ runtime.manager.contextManager.clearSelectedDomElements(path) } - // The inline mini-composer over a selected element sends a chat turn; the - // element is already an app_dom_selector chip, so it rides along as context. - // Mirror the composer: while another send holds the chat — streaming, in - // preflight, or waiting for the transcript to be restored — queue it (a second - // concurrent sendRequest would race the shared abortController / streaming - // buffers) — it auto-sends when the current turn completes. + // The inline mini-composer sits over ONE element: with several selected, the model could not + // tell which one the prompt is about. Match appPath too, as selectors are generated per app + // and collide across them. function onInlinePrompt(selector: string, prompt: string) { - // Snapshot the selection synchronously at submit time so a re-selection - // during the async send preflight (immediate path) or before the queue - // flushes (loading path) can't swap the context. Scope the DOM chips to the - // anchored element: the inline prompt sits over ONE element, so with several - // selected, drop the others (a multi-select would otherwise send every - // selector and the model couldn't tell which one the prompt is about). - // Match appPath too — selectors are generated per app and collide across - // them, and a restored draft can legitimately hold chips from several apps. - // Non-DOM context is kept. - const snapshot = runtime.manager.contextManager + const { contextManager } = runtime.manager + const picks = contextManager .getSelectedContext() - .filter( - (c) => c.type !== 'app_dom_selector' || (c.selector === selector && c.appPath === path) - ) - if (runtime.manager.loading || runtime.manager.sendInFlight || runtime.manager.sendPending) { - runtime.manager.queueMessage(prompt, [], snapshot) - } else { - void runtime.manager.sendRequest({ instructions: prompt, contextOverride: snapshot }) - } + .filter((c) => c.type === 'app_dom_selector') + .filter((c) => c.selector === selector && c.appPath === path) + contextManager.removeSelectedDomElement(selector, path) + runtime.manager.sendOrQueue(prompt, picks) } // The preview host keeps every opened tab mounted, so registering on mount would diff --git a/frontend/src/lib/components/sessions/SessionWrapper.dom.test.ts b/frontend/src/lib/components/sessions/SessionWrapper.dom.test.ts index 241cd06921..571976b814 100644 --- a/frontend/src/lib/components/sessions/SessionWrapper.dom.test.ts +++ b/frontend/src/lib/components/sessions/SessionWrapper.dom.test.ts @@ -5,11 +5,19 @@ import { copilotInfo, copilotWorkspace } from '$lib/aiStore' import { loadCopilot } from '$lib/components/copilot/loadCopilot' import { workspaceStore } from '$lib/stores' import { sessionState, type Session } from './sessionState.svelte' +import { openSourceInSession } from './sessionSwitch.svelte' +import { AIChatManager } from '../copilot/chat/AIChatManager.svelte' +import { createCodeSelection } from '../copilot/chat/context' import SessionWrapper from './SessionWrapper.svelte' // Measures itself, which jsdom has no layout for. Its content (the chat) is not under test. vi.mock('svelte-splitpanes', () => ({ Pane: () => {}, Splitpanes: () => {} })) +vi.mock('$lib/navigation', async (importOriginal) => ({ + ...(await importOriginal<typeof import('$lib/navigation')>()), + goto: vi.fn() +})) + let requests: string[] = [] let version = 1 vi.mock('$lib/gen', async (importOriginal) => { @@ -30,7 +38,10 @@ vi.mock('$lib/gen', async (importOriginal) => { }) let component: ReturnType<typeof mount> | undefined -afterEach(() => component && unmount(component)) +afterEach(() => { + if (component) unmount(component) + vi.restoreAllMocks() +}) // The page is on `parent`, whose config changes before the session comes on screen. async function showSession(workspace: string) { @@ -63,3 +74,25 @@ it("a session in the page's workspace refreshes the tab's copy when it comes on await showSession('parent') expect(get(copilotInfo).aiModels[0]?.model).toBe('parent-2') }) + +it("sends a new session's first message with the code handed over", async () => { + const send = vi.spyOn(AIChatManager.prototype, 'sendOrQueue').mockImplementation(() => {}) + const selection = createCodeSelection( + { kind: 'script', path: 'f/a/b' }, + { content: 'return 1', startLine: 2, endLine: 2, lang: 'bun' } + ) + await openSourceInSession( + { target: { kind: 'script', path: 'f/a/b' } }, + { seedPrompt: 'make it 2', autoSend: true, seedPick: selection } + ) + const id = sessionState.currentSessionId! + component = mount(SessionWrapper, { + target: document.body, + props: { sessionId: id, onScreen: true, previewTabName: () => '' } + }) + flushSync() + + await vi.waitFor(() => expect(send).toHaveBeenCalledOnce()) + expect(send).toHaveBeenCalledWith('make it 2', [selection]) + expect(sessionState.sessions.find((s) => s.id === id)?.autoSendPick).toBeUndefined() +}) diff --git a/frontend/src/lib/components/sessions/SessionWrapper.svelte b/frontend/src/lib/components/sessions/SessionWrapper.svelte index 7cdff9eb8d..53c2362807 100644 --- a/frontend/src/lib/components/sessions/SessionWrapper.svelte +++ b/frontend/src/lib/components/sessions/SessionWrapper.svelte @@ -10,6 +10,7 @@ <script lang="ts"> import { setContext, untrack } from 'svelte' + import { setImageOpener } from '$lib/components/common/image/imageOpener' import { Pane, Splitpanes } from 'svelte-splitpanes' import type AIChat from '$lib/components/copilot/chat/AIChat.svelte' import ComposerPlaceholder from '$lib/components/copilot/chat/ComposerPlaceholder.svelte' @@ -61,7 +62,7 @@ getSessionDraftAttachments, setSessionDraftAttachments, peekSessionAutoSend, - getSessionAutoSendDomElement, + getSessionAutoSendPick, takeSessionAutoSend, reconcileAfterWorkspaceChange, renameSession, @@ -111,6 +112,7 @@ if (runtime) { setContext<AIChatManager>('aiChatManager', runtime.manager) + setImageOpener((source, label) => runtime.manager.openImage?.(source, label)) } // Reactive session reference (mutations to summary/target propagate via the $state proxy). @@ -192,14 +194,14 @@ if (!session?.autoSendDraftAt || !runtime) return untrack(() => { const prompt = getSessionDraftPrompt(sessionId) - const domElement = getSessionAutoSendDomElement(sessionId) + const pick = getSessionAutoSendPick(sessionId) // takeSessionAutoSend clears the intent whether or not it is still // fresh, so this cannot re-enter on the next dependency change. if (!takeSessionAutoSend(sessionId) || !prompt) return // sendOrQueue, not sendRequest: a reused session may already be mid-turn. // Each request awaits the config of the committed workspace, so this // cannot race the model config on a cold session. - runtime.manager.sendOrQueue(prompt, domElement ? [domElement] : undefined) + runtime.manager.sendOrQueue(prompt, pick ? [pick] : undefined) }) }) diff --git a/frontend/src/lib/components/sessions/openInSessionContext.ts b/frontend/src/lib/components/sessions/openInSessionContext.ts index 27284802cc..cd877b1f9a 100644 --- a/frontend/src/lib/components/sessions/openInSessionContext.ts +++ b/frontend/src/lib/components/sessions/openInSessionContext.ts @@ -1,4 +1,4 @@ -import { getContext, setContext } from 'svelte' +import { getContext, setContext, tick } from 'svelte' import type { OpenInSessionSource } from './OpenInSessionButton.svelte' // The "Open in AI session" hand-off, published by the component that owns the @@ -21,3 +21,21 @@ export function setOpenInSessionHandoff(handoff: OpenInSessionHandoff): void { export function getOpenInSessionHandoff(): OpenInSessionHandoff | undefined { return getContext<OpenInSessionHandoff | undefined>(KEY) } + +/** The hand-off with an editor's in-flight keystrokes materialized first: the session loads the + * item from its draft, which would otherwise miss the last (sub-second) edits. */ +export function withEditorFlush( + source: OpenInSessionSource, + flushEditor: () => void +): OpenInSessionSource { + return { + ...source, + beforeOpen: async () => { + flushEditor() + // The flush lands in the draft store through an effect; let it run + // before the hand-off persists that store. + await tick() + await source.beforeOpen?.() + } + } +} diff --git a/frontend/src/lib/components/sessions/pageDrawerSession.ts b/frontend/src/lib/components/sessions/pageDrawerSession.ts index 99137be3f0..d41e7c22b2 100644 --- a/frontend/src/lib/components/sessions/pageDrawerSession.ts +++ b/frontend/src/lib/components/sessions/pageDrawerSession.ts @@ -50,6 +50,12 @@ async function flushOrRefuse(query: Parameters<typeof UserDraftDbSyncer.flush>[0 throw new Error('This page has changes that are not valid JSON. Fix them first.') } await UserDraftDbSyncer.flush(query) + assertDraftSaved(query) +} + +/** Throws when the last save of this draft did not land: a save reports a failed or conflicting + * POST through its state. */ +export function assertDraftSaved(query: Parameters<typeof UserDraftDbSyncer.flush>[0]): void { if (UserDraftDbSyncer.getConflict(query).conflict) { throw new Error( 'This draft has a newer conflicting version on the server. Resolve it here before opening a session.' diff --git a/frontend/src/lib/components/sessions/previewRouter.test.ts b/frontend/src/lib/components/sessions/previewRouter.test.ts index cdfbb63a45..fdab8e0775 100644 --- a/frontend/src/lib/components/sessions/previewRouter.test.ts +++ b/frontend/src/lib/components/sessions/previewRouter.test.ts @@ -4,6 +4,8 @@ import { describeLocation, draftFriendlyLeaf, drawerAnchorFor, + imageUrl, + parseImageRoute, showsView, itemDisplayName, matchReusablePage, @@ -548,3 +550,26 @@ describe('run form route', () => { expect(parseRunFormRoute('artifact:abc#Plan')).toBeNull() }) }) + +describe('image routes', () => { + it('round-trips every image source, slashes in a name or URL included', () => { + const sources = [ + { kind: 'file', name: 'screens/icons/logo.png' }, + { kind: 'message', hash: '36976501-1qvb' }, + { kind: 'result', workspace: 'admins', jobId: '01a2', format: 'png' }, + { kind: 'result', workspace: 'admins', jobId: '01a2', format: 'jpeg', nodeId: 'a' }, + { + kind: 'result', + workspace: 'admins', + jobId: '01a2', + format: 'png', + path: ['render_all', 1] + }, + { kind: 'url', url: '/api/w/admins/job_helpers/load_image_preview?file_key=out/x.png' } + ] as const + for (const source of sources) { + expect(parseImageRoute(imageUrl(source, 'My image'))).toEqual({ source, label: 'My image' }) + } + expect(parseImageRoute('image:result/admins/01a2/bmp')).toBeNull() + }) +}) diff --git a/frontend/src/lib/components/sessions/previewRouter.ts b/frontend/src/lib/components/sessions/previewRouter.ts index 8147de8334..98ade471ef 100644 --- a/frontend/src/lib/components/sessions/previewRouter.ts +++ b/frontend/src/lib/components/sessions/previewRouter.ts @@ -106,11 +106,36 @@ export type PreviewTarget = | { type: 'runform'; toolCallId: string; label: string } | { type: 'pageitem'; ref: PageItemRef } | { type: 's3file'; file: S3FileRef } + | { type: 'image'; source: ImageSource; label: string } /** A file in the workspace's object storage: its key, in the storage it names (the primary * one when none). */ export type S3FileRef = { s3: string; storage?: string } +/** Where an image tab's bytes come from: a file the session linked (addressed by its + * name in the attached-files store), an image the user sent in a chat message (by a hash + * of its data URL, since message images carry no id), a job's inline image result (by the + * job, refetched rather than carried: the tab url is persisted and the bytes run to + * megabytes), or an image the API serves at a URL (an S3 result's preview). */ +export type ImageSource = + | { kind: 'file'; name: string } + | { kind: 'message'; hash: string } + | { + kind: 'result' + workspace: string + jobId: string + nodeId?: string + format: ImageResultFormat + /** Where the image sits inside the result, when it is not the result itself + * (a `render_all` child). */ + path?: ResultPath + } + | { kind: 'url'; url: string } + +export type ImageResultFormat = 'png' | 'jpeg' | 'gif' +export type ResultPath = (string | number)[] +const IMAGE_RESULT_FORMATS: readonly string[] = ['png', 'jpeg', 'gif'] + /** * Which side of an item to open when the opener is showing the reader something * that already exists, rather than something it just wrote: the deployed page, @@ -223,7 +248,8 @@ export function canonicalizeObservedLoc(loc: string): string { parseArtifactRoute(loc) || parseRunFormRoute(loc) || parsePageItemRoute(loc) || - parseS3FileRoute(loc) + parseS3FileRoute(loc) || + parseImageRoute(loc) ) return loc try { @@ -305,6 +331,9 @@ export function describeLocation(loc: string): PreviewLocation { // Identity is the call, never the label: that carries the script's summary, so folding it // in would open a second tab for the same form whenever the summary differed. if (runForm) return { identity: `runform:${runForm.toolCallId}`, view: '', anchor: '' } + // Identity is the source, never the label. + const image = parseImageRoute(loc) + if (image) return { identity: imageUrl(image.source, ''), view: '', anchor: '' } const pageItem = parsePageItemRoute(loc) if (pageItem) return { identity: pageItemUrl(pageItem), view: '', anchor: '' } const s3File = parseS3FileRoute(loc) @@ -494,6 +523,8 @@ export function previewLocationLabel(url: string): string { if (runForm) return runForm.label || 'Run form' const s3File = parseS3FileRoute(url) if (s3File) return s3File.s3.split('/').pop() || s3File.s3 + const image = parseImageRoute(url) + if (image) return image.label || 'Image' const pageItem = parsePageItemRoute(url) if (pageItem) return pageItem.path.split('/').pop() || pageItem.path const page = matchReusablePage(url) @@ -642,6 +673,79 @@ export function s3FileUrl(file: S3FileRef): string { return `s3file:${encodeURIComponent(file.storage || '_default_')}/${key}` } +// An image tab: `image:file/<name>` or `image:msg/<hash>`, the label in the hash. A scheme for +// the same reason as artifacts — the tab mounts a viewer, there is no page to frame. +export function parseImageRoute(url: string): { source: ImageSource; label: string } | null { + const m = url.match(/^image:(file|msg|result|url)\/([^?#]+)(?:#(.*))?$/) + if (!m) return null + let parts: string[] + let label = '' + try { + parts = m[2].split('/').map(decodeURIComponent) + label = m[3] ? decodeURIComponent(m[3]) : '' + } catch { + return null + } + const source = imageSourceOf(m[1], parts) + return source ? { source, label } : null +} + +function imageSourceOf(kind: string, parts: string[]): ImageSource | undefined { + if (kind === 'file' && parts.length === 1) return { kind: 'file', name: parts[0] } + if (kind === 'msg' && parts.length === 1) return { kind: 'message', hash: parts[0] } + if (kind === 'url' && parts.length === 1) return { kind: 'url', url: parts[0] } + if (kind === 'result' && parts.length >= 3 && parts.length <= 5) { + const [workspace, jobId, format, nodeId, pathJson] = parts + if (!IMAGE_RESULT_FORMATS.includes(format)) return undefined + const path = pathJson ? parseResultPath(pathJson) : undefined + if (pathJson && !path) return undefined + return { + kind: 'result', + workspace, + jobId, + format: format as ImageResultFormat, + ...(nodeId ? { nodeId } : {}), + ...(path ? { path } : {}) + } + } + return undefined +} + +function parseResultPath(json: string): ResultPath | undefined { + try { + const path: unknown = JSON.parse(json) + return Array.isArray(path) && + path.length > 0 && + path.every((k) => typeof k === 'string' || typeof k === 'number') + ? path + : undefined + } catch { + return undefined + } +} + +// Every segment is encoded on its own, so a `/` inside a file name or URL stays one segment. +export function imageUrl(source: ImageSource, label: string): string { + const segments = + source.kind === 'file' + ? ['file', source.name] + : source.kind === 'message' + ? ['msg', source.hash] + : source.kind === 'url' + ? ['url', source.url] + : [ + 'result', + source.workspace, + source.jobId, + source.format, + // The node segment is kept, empty, when a path follows it. + ...(source.nodeId || source.path?.length ? [source.nodeId ?? ''] : []), + ...(source.path?.length ? [JSON.stringify(source.path)] : []) + ] + const [kind, ...rest] = segments + return `image:${kind}/${rest.map(encodeURIComponent).join('/')}${label ? `#${encodeURIComponent(label)}` : ''}` +} + export function runFormUrl(toolCallId: string, label: string): string { return `runform:${encodeURIComponent(toolCallId)}#${encodeURIComponent(label)}` } @@ -676,6 +780,7 @@ export type PreviewSlot = | { kind: 'artifact'; id: string; version?: number } | { kind: 'runform'; toolCallId: string } | { kind: 's3file'; file: S3FileRef } + | { kind: 'image'; source: ImageSource } | { kind: 'pageitem'; ref: PageItemRef } | { kind: 'pagelist'; path: string } | { kind: 'run'; jobId: string; workspace?: string } @@ -700,6 +805,8 @@ export function resolvePreviewTab(url: string): PreviewSlot { if (runForm) return { kind: 'runform', toolCallId: runForm.toolCallId } const s3File = parseS3FileRoute(url) if (s3File) return { kind: 's3file', file: s3File } + const image = parseImageRoute(url) + if (image) return { kind: 'image', source: image.source } const pageItem = parsePageItemRoute(url) if (pageItem) return { kind: 'pageitem', ref: pageItem } const route = barePath(url) @@ -741,6 +848,7 @@ export function workspacePageHref(location: string): string | undefined { case 'artifact': case 'runform': case 's3file': + case 'image': return undefined case 'pageitem': return pageItemPageHref(slot.ref) diff --git a/frontend/src/lib/components/sessions/sessionMirror.svelte.ts b/frontend/src/lib/components/sessions/sessionMirror.svelte.ts index 657f120e98..d5ae49f121 100644 --- a/frontend/src/lib/components/sessions/sessionMirror.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionMirror.svelte.ts @@ -67,6 +67,26 @@ import { type PushBody } from './sessionMirrorPlan' +/** A session preview tab loads the app in a frame of the app itself. Its storage is the + * page's, so the backup is left to the page: the frame only writes marks and asks the page to + * flush them, since its own restore would hold the user's lock against the page's flushes, and + * Firefox rejects a lock request from a frame's document while it is being removed. A frame + * under another origin (the app embedded in another site) keeps its own backup: no top-level + * page of the app reads its storage. */ +const inAppFrame = BROWSER && window.self !== window.top && sameOriginTop() + +/** Sent to the top page, not signalled through `storage` events: those reach every tab of + * the user, and each would flush a mark the page already uploads. */ +const FRAME_FLUSH_MESSAGE = 'wm-session-mirror-flush' + +function sameOriginTop(): boolean { + try { + return window.top?.location.origin === window.location.origin + } catch { + return false + } +} + /** A flush waits for the marks to go quiet this long. */ const QUIET_MS = 15_000 /** ...but never longer than this after the first unflushed mark. */ @@ -352,12 +372,17 @@ function clearTimers(): void { } function scheduleFlush(): void { + if (inAppFrame) { + window.top?.postMessage({ type: FRAME_FLUSH_MESSAGE }, window.location.origin) + return + } clearTimeout(quietTimer) quietTimer = setTimeout(runFlush, QUIET_MS) maxTimer ??= setTimeout(runFlush, MAX_DELAY_MS) } function runFlush(): void { + if (inAppFrame) return clearTimers() void enqueue(flush) } @@ -1557,7 +1582,7 @@ async function restoreWorkspace( * touched; only ones this browser lacks are brought back. */ export function restoreSessionBackups(currentWorkspace: string): void { - if (!BROWSER) return + if (!BROWSER || inAppFrame) return // A restore writes an absent session's pieces page by page and prunes what an earlier // one staged: two tabs doing that at once would write over each other, so it runs only // under the tab lock. Where Web Locks do not exist (a plain http origin), the browser @@ -1632,11 +1657,18 @@ if (BROWSER) { unwritableMarks.clear() if (email) setTimeout(runFlush, STARTUP_DELAY_MS) }) - // A tab going to the background may not come back: carry what it has now. if (typeof document !== 'undefined') { + // A tab going to the background may not come back: carry what it has now. document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') runFlush() }) + if (!inAppFrame) { + window.addEventListener('message', (e) => { + if (e.origin === window.location.origin && e.data?.type === FRAME_FLUSH_MESSAGE) { + scheduleFlush() + } + }) + } } } diff --git a/frontend/src/lib/components/sessions/sessionMirrorPlan.ts b/frontend/src/lib/components/sessions/sessionMirrorPlan.ts index 386e65308f..84f25cdde2 100644 --- a/frontend/src/lib/components/sessions/sessionMirrorPlan.ts +++ b/frontend/src/lib/components/sessions/sessionMirrorPlan.ts @@ -79,7 +79,7 @@ export function isFallbackStorage(name: string): boolean { /** * The part of a session record the backup keeps. Left out on purpose: `name` (a * per-browser legacy label), the unsent-draft fields (`pending_*`, `draftPrompt`, - * `autoSendDraftAt`, `autoSendDomElement`), `workspace_root_id` (derived on import), + * `autoSendDraftAt`, `autoSendPick`), `workspace_root_id` (derived on import), * `transient`, `restoredAt` (this browser's clock), and the two fields reading a session bumps (`lastSeenCount`, * `lastActivityAt`) — so opening a session and reading its new messages never costs a push. */ diff --git a/frontend/src/lib/components/sessions/sessionPreviewTabs.svelte.ts b/frontend/src/lib/components/sessions/sessionPreviewTabs.svelte.ts index 5e617be5de..8d1a67e8c0 100644 --- a/frontend/src/lib/components/sessions/sessionPreviewTabs.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionPreviewTabs.svelte.ts @@ -16,6 +16,8 @@ import { promptSafe, parsePreviewItemRoute, parseRunFormRoute, + parseImageRoute, + imageUrl, previewLocationLabel, resolvePreviewTab, runFormUrl, @@ -112,6 +114,7 @@ function targetUrl(target: PreviewTarget, onto?: SessionPreviewTab): string { } if (target.type === 'runform') return runFormUrl(target.toolCallId, target.label) if (target.type === 's3file') return s3FileUrl(target.file) + if (target.type === 'image') return imageUrl(target.source, target.label) // A re-point with no mode keeps the side the tab is already on, so an AI write to // an item the user left on View does not yank them back to the editor. const mode = target.mode ?? (onto ? (parsePreviewItemRoute(onto.url)?.mode ?? 'edit') : 'edit') @@ -851,6 +854,7 @@ export function describePreview( const lines = tabs.map((t) => { const where = whereIs(t) const artifact = parseArtifactRoute(where) + const image = parseImageRoute(where) const pageItem = parsePageItemRoute(where) const s3File = parseS3FileRoute(where) const page = matchPreviewPage(where) @@ -860,19 +864,27 @@ export function describePreview( ? // A pinned tab is not showing what the assistant last wrote, and nothing else in this // summary would tell it so. `artifact "${artifact.name || 'Artifact'}"${artifact.version ? ` (pinned to v${artifact.version})` : ''}` - : s3File - ? `object storage file "${s3File.s3}"${s3File.storage ? ` in storage "${s3File.storage}"` : ''}` - : pageItem - ? `${pageItemKindLabel(pageItem).toLowerCase()} "${pageItem.path}"` - : page - ? `page "${page.label}"${previewLocationDetail(where)}` - : pipelineFolder - ? `pipeline "${pipelineFolder}"` - : route - ? `${route.raw_app ? 'raw_app' : route.kind} "${route.itemPath}"` - : // Trigger list pages land here (they're outside PREVIEW_PAGES), and - // their `#<path>` is the trigger the drawer has open. - `${barePath(where)}${previewLocationDetail(where)}` + : image + ? image.source.kind === 'file' + ? `image file "${image.source.name}"` + : image.source.kind === 'message' + ? `image "${image.label || 'Image'}" from a chat message` + : image.source.kind === 'result' + ? `image result of job ${image.source.jobId}${image.source.nodeId ? ` (step ${image.source.nodeId})` : ''}` + : `image "${image.label || 'Image'}"` + : s3File + ? `object storage file "${s3File.s3}"${s3File.storage ? ` in storage "${s3File.storage}"` : ''}` + : pageItem + ? `${pageItemKindLabel(pageItem).toLowerCase()} "${pageItem.path}"` + : page + ? `page "${page.label}"${previewLocationDetail(where)}` + : pipelineFolder + ? `pipeline "${pipelineFolder}"` + : route + ? `${route.raw_app ? 'raw_app' : route.kind} "${route.itemPath}"` + : // Trigger list pages land here (they're outside PREVIEW_PAGES), and + // their `#<path>` is the trigger the drawer has open. + `${barePath(where)}${previewLocationDetail(where)}` const slotKind = resolvePreviewTab(t.url).kind const live = slotKind === 'editor' || slotKind === 'pageitem' diff --git a/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts b/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts index 2c23953b41..7ed6c77c52 100644 --- a/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts @@ -227,6 +227,7 @@ function tabUsageKey(slot: PreviewSlot): string { if (slot.kind === 'editor') return slot.editorKind if (slot.kind === 'viewer') return `view_${slot.viewerKind}` if (slot.kind === 'artifact') return 'artifact' + if (slot.kind === 'image') return 'image' return slot.kind === 'runform' ? 'run_form' : 'page' } @@ -757,6 +758,9 @@ function createRuntime(session: Session): SessionRuntime { manager.openS3File = (file) => { previewTabs.open({ type: 's3file', file }) } + manager.openImage = (source, label) => { + previewTabs.open({ type: 'image', source, label }) + } // Key the store before any configureGlobalMode runs, so a new session's first create shows at once. void manager.artifacts.setSession(session.id) diff --git a/frontend/src/lib/components/sessions/sessionState.svelte.ts b/frontend/src/lib/components/sessions/sessionState.svelte.ts index f5fa63b729..e540d32599 100644 --- a/frontend/src/lib/components/sessions/sessionState.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionState.svelte.ts @@ -29,7 +29,7 @@ import { import { deleteSessionHandEdits } from './sessionHandEdits.svelte' import { deleteSessionChats } from '../copilot/chat/HistoryManager.svelte' import type { DraftAttachments } from '../copilot/chat/messageDraft.svelte' -import type { AppDomSelectorElement } from '../copilot/chat/context' +import type { PickContext } from '../copilot/chat/context' import { markSessionDirty, markSessionRemoved, @@ -203,10 +203,10 @@ export type Session = { // would otherwise leave a session armed forever and fire on some later visit. // Consumed exactly once, by takeSessionAutoSend. autoSendDraftAt?: number - // The element a preview pick hands over with the auto-sent prompt, sent as its - // chip. Lives and dies with `autoSendDraftAt`: a prompt like "make this bigger" - // must never go out without the element it names. - autoSendDomElement?: AppDomSelectorElement + // The preview element or code selection handed over with the auto-sent prompt, sent as + // its chip. Lives and dies with `autoSendDraftAt`: a prompt like "make this bigger" + // must never go out without what it names. + autoSendPick?: PickContext } // One preview tab: `url` is the URL we command the iframe to load, `loc` the @@ -482,17 +482,17 @@ const AUTO_SEND_TTL_MS = 5 * 60_000 // Mark this session's draft prompt for sending on arrival. Written straight to // the record (not via setSessionDraftPrompt's debounce) because the navigation // that follows must not outrun it. -export function setSessionAutoSend(sessionId: string, domElement?: AppDomSelectorElement): void { +export function setSessionAutoSend(sessionId: string, pick?: PickContext): void { const s = sessionState.sessions.find((x) => x.id === sessionId) if (!s) return s.autoSendDraftAt = Date.now() - s.autoSendDomElement = domElement + s.autoSendPick = pick persistTouched(s) } -// The element armed with the auto-send intent; read before takeSessionAutoSend clears both. -export function getSessionAutoSendDomElement(sessionId: string): AppDomSelectorElement | undefined { - return sessionState.sessions.find((x) => x.id === sessionId)?.autoSendDomElement +// The pick armed with the auto-send intent; read before takeSessionAutoSend clears both. +export function getSessionAutoSendPick(sessionId: string): PickContext | undefined { + return sessionState.sessions.find((x) => x.id === sessionId)?.autoSendPick } function autoSendIsFresh(s: Session | undefined): boolean { @@ -515,7 +515,7 @@ export function takeSessionAutoSend(sessionId: string): boolean { if (!s?.autoSendDraftAt) return false const fresh = autoSendIsFresh(s) delete s.autoSendDraftAt - delete s.autoSendDomElement + delete s.autoSendPick persistTouched(s) return fresh } diff --git a/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts b/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts index 3549ae9347..22ec909788 100644 --- a/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts @@ -29,16 +29,16 @@ import { homeComposerContext } from './homeComposerContext.svelte' // Type-only: erased at compile time, so the component graph stays out of this // navigation seam (see the dynamic import in openEditorInSession). import type { OpenInSessionSource } from './OpenInSessionButton.svelte' -import type { AppDomSelectorElement } from '../copilot/chat/context' +import type { PickContext } from '../copilot/chat/context' import { presetScopeFor } from '../copilot/chat/workingScope' -// `seedDomElement` rides only with `autoSend`: it is the chip of the prompt being sent. +// `seedPick` rides only with `autoSend`: it is the chip of the prompt being sent. // `untilStarted` keeps the session out of storage until the user starts it, for an item that // is kept on its own (a new app's draft) and so loses nothing when the session goes. type SeedOpts = { seedPrompt?: string autoSend?: boolean - seedDomElement?: AppDomSelectorElement + seedPick?: PickContext untilStarted?: boolean } @@ -204,7 +204,7 @@ async function sessionHrefFor( setSessionWorkingIn(session.id, workingIn, workingIn ? 'preset' : undefined) if (opts?.seedPrompt) { setSessionDraftPrompt(session.id, opts.seedPrompt) - if (opts.autoSend) setSessionAutoSend(session.id, opts.seedDomElement) + if (opts.autoSend) setSessionAutoSend(session.id, opts.seedPick) } if (url) { // Dynamic import: a static one would drag the runtime's heavy graph @@ -229,7 +229,7 @@ export async function openSourceInSession( const opts = { seedPrompt: overrides?.seedPrompt ?? source.seedPrompt, autoSend: overrides?.autoSend ?? source.autoSend, - seedDomElement: overrides?.seedDomElement, + seedPick: overrides?.seedPick, untilStarted: overrides?.untilStarted } if (source.target) { diff --git a/frontend/src/lib/components/sessions/sessionSwitch.test.ts b/frontend/src/lib/components/sessions/sessionSwitch.test.ts index 758af967f4..78c86deeba 100644 --- a/frontend/src/lib/components/sessions/sessionSwitch.test.ts +++ b/frontend/src/lib/components/sessions/sessionSwitch.test.ts @@ -7,7 +7,7 @@ import { startSessionWithPrompt } from './sessionSwitch.svelte' import { - getSessionAutoSendDomElement, + getSessionAutoSendPick, homeDraft, peekSessionAutoSend, sessionState, @@ -172,12 +172,12 @@ describe('auto-send intent', () => { try { await openSourceInSession( { target: { kind: 'raw_app', path: 'u/me/app' } }, - { seedPrompt: 'make this bigger', autoSend: true, seedDomElement: el } + { seedPrompt: 'make this bigger', autoSend: true, seedPick: el } ) createdId = sessionState.currentSessionId! - expect(getSessionAutoSendDomElement(createdId)).toEqual(el) + expect(getSessionAutoSendPick(createdId)).toEqual(el) expect(takeSessionAutoSend(createdId)).toBe(true) - expect(getSessionAutoSendDomElement(createdId)).toBeUndefined() + expect(getSessionAutoSendPick(createdId)).toBeUndefined() } finally { sessionState.sessions = sessionState.sessions.filter((s) => s.id !== createdId) sessionState.currentSessionId = prevCurrent diff --git a/frontend/src/lib/components/settings/AIUserSettings.svelte b/frontend/src/lib/components/settings/AIUserSettings.svelte index de83b15158..6b9aecd7a8 100644 --- a/frontend/src/lib/components/settings/AIUserSettings.svelte +++ b/frontend/src/lib/components/settings/AIUserSettings.svelte @@ -36,9 +36,7 @@ } </script> -<div class="border border-border-light rounded-md p-4 h-full"> - <h2 class="text-emphasis text-sm font-semibold mb-2">AI user settings</h2> - +<div> <div class="flex flex-col gap-4"> <Toggle on:change={(e) => { diff --git a/frontend/src/lib/components/settings/AdminRelianceNotice.svelte b/frontend/src/lib/components/settings/AdminRelianceNotice.svelte new file mode 100644 index 0000000000..5840bfe5b3 --- /dev/null +++ b/frontend/src/lib/components/settings/AdminRelianceNotice.svelte @@ -0,0 +1,153 @@ +<script lang="ts"> + import { GranularAclService, TokenService, type TokenAdminReliance } from '$lib/gen' + import { Alert, Button } from '../common' + import CollapseLink from '../CollapseLink.svelte' + import { sendUserToast } from '$lib/toast' + import { resource } from 'runed' + + interface Props { + /** The workspaces the token reaches; undefined for every workspace the user is in. */ + workspaceIds: string[] | undefined + /** The token's scopes; undefined or empty for an unscoped token. */ + scopes: string[] | undefined + readOnly?: boolean + } + + let { workspaceIds, scopes, readOnly = false }: Props = $props() + + let adding = $state(false) + + const res = resource( + () => ({ + ws: workspaceIds ? [...workspaceIds] : undefined, + sc: scopes && scopes.length > 0 ? [...scopes] : undefined, + ro: readOnly + }), + async ({ ws, sc, ro }, _, { signal }) => { + if (ws && ws.length === 0) return [] + const out = await TokenService.getTokenAdminReliance({ + requestBody: { workspace_ids: ws, scopes: sc, read_only: ro } + }).catch(() => []) + // A superseded fetch must not overwrite the newer one. + if (signal.aborted) throw new DOMException('superseded', 'AbortError') + return out + }, + { debounce: 300 } + ) + const reliance = $derived(res.current ?? []) + + async function addMe(r: TokenAdminReliance, folders: string[]) { + adding = true + try { + for (const folder of folders) { + await GranularAclService.addGranularAcls({ + workspace: r.workspace_id, + path: folder, + kind: 'folder', + requestBody: { owner: `u/${r.username}`, write: true } + }) + } + sendUserToast( + folders.length === 1 + ? `Added you as a writer of ${folders[0]}` + : `Added you as a writer of ${folders.length} folders` + ) + } catch (e) { + sendUserToast(`Could not add you to the folder: ${e?.body ?? e}`, true) + } + adding = false + await res.refetch() + } + + const many = $derived(reliance.length > 1) + + function foldersLabel(r: TokenAdminReliance) { + const count = r.folders_total === 1 ? 'A folder' : `${r.folders_total} folders` + return `${count} ${r.folders_write ? 'you cannot write to' : 'you are not a member of'}` + } +</script> + +{#if reliance.length > 0} + <Alert + type="warning" + title="Without your admin rights, this token reaches less than you do" + size="xs" + > + <div class="flex flex-col gap-3"> + <p> + Workspace admin rights are off, so the token, and the jobs it starts, act as a regular + member. Your admin role gives you the access below; the token will not have it. + </p> + <!-- Up to 50 workspaces of up to 50 folders each: unbounded, this list pushes the form + it sits in (the CLI login page, the token drawer) out of the window. --> + <div class="flex flex-col gap-3 max-h-64 overflow-y-auto"> + {#each reliance as r (r.workspace_id)} + <div class="flex flex-col gap-1.5"> + {#if many} + <span class="font-semibold text-emphasis">In {r.workspace_id}</span> + {/if} + {#if r.folders_total > 0} + <CollapseLink text={foldersLabel(r)}> + <div class="flex flex-wrap items-center gap-x-3 gap-y-1"> + {#each r.folders as folder (folder)} + <span class="inline-flex flex-wrap items-center gap-1"> + <code class="break-all">f/{folder}</code> + <Button + variant="default" + unifiedSize="2xs" + disabled={adding} + onclick={() => addMe(r, [folder])}>Add me as writer</Button + > + </span> + {/each} + {#if r.folders.length > 1} + <span class="inline-flex"> + <Button + variant="default" + unifiedSize="2xs" + disabled={adding} + onclick={() => addMe(r, r.folders)} + > + Add me to {r.folders.length === r.folders_total + ? 'all of them' + : `these ${r.folders.length}`} + </Button> + </span> + {/if} + </div> + </CollapseLink> + {/if} + {#if r.assets.length > 0} + <div class="flex flex-col gap-0.5"> + <span>What the token's scripts and flows use, outside your own access:</span> + <ul class="list-disc pl-4"> + {#each r.assets as a (`${a.runnable_kind}:${a.runnable_path}:${a.kind}:${a.path}`)} + <li> + <code>{a.runnable_path}</code> uses {a.kind} <code>{a.path}</code> + </li> + {/each} + </ul> + </div> + {/if} + {#if r.other_users_items > 0} + <span> + {r.other_users_items === 1 + ? "1 item in another user's space is not shared with you. Ask its owner to share it, or move it into a folder." + : `${r.other_users_items} items in other users' spaces are not shared with you. Ask their owners to share them, or move them into a folder.`} + </span> + {/if} + {#if r.admin_only.length > 0} + <span> + It will be refused what only an admin can do: {r.admin_only.join('; ')}. Turn on + Workspace admin rights if it needs that. + </span> + {/if} + </div> + {/each} + </div> + <p class="text-2xs text-secondary"> + Variables, and resources a script reads from a path built at runtime, are not checked. + </p> + </div> + </Alert> +{/if} diff --git a/frontend/src/lib/components/settings/CreateToken.svelte b/frontend/src/lib/components/settings/CreateToken.svelte index e96cfad47d..6cdbf8fe97 100644 --- a/frontend/src/lib/components/settings/CreateToken.svelte +++ b/frontend/src/lib/components/settings/CreateToken.svelte @@ -1,14 +1,24 @@ <script lang="ts"> import { onMount, untrack } from 'svelte' - import { superadmin, userWorkspaces, usersWorkspaceStore, type UserWorkspace } from '$lib/stores' - import { Button, Skeleton } from '../common' + import { + enterpriseLicense, + superadmin, + userStore, + userWorkspaces, + usersWorkspaceStore, + type UserWorkspace + } from '$lib/stores' + import { Alert, Button, Skeleton } from '../common' import { triggerableByAI } from '$lib/actions/triggerableByAI.svelte' import Toggle from '../Toggle.svelte' - import { SettingService, UserService, type NewToken } from '$lib/gen' + import { SettingService, SettingsService, UserService, type NewToken } from '$lib/gen' import { listEveryWorkspace, mcpTokenUrlDisabled } from '$lib/mcpAuth' import { apiBaseUrl } from '$lib/apiBaseUrl.svelte' import TokenDisplay from './TokenDisplay.svelte' + import TokenInspector from './TokenInspector.svelte' + import CollapseLink from '../CollapseLink.svelte' import ScopesPicker from './ScopesPicker.svelte' + import AdminRelianceNotice from './AdminRelianceNotice.svelte' import { parseMaxTokenExpirationDays } from '$lib/tokenExpiration' import TextInput from '../text_input/TextInput.svelte' @@ -17,6 +27,8 @@ import ClipboardPanel from '../details/ClipboardPanel.svelte' import McpAccessPicker, { type McpAccess } from '../mcp/McpAccessPicker.svelte' import MultiSelect from '../select/MultiSelect.svelte' + import ToggleButtonGroup from '../common/toggleButton-v2/ToggleButtonGroup.svelte' + import ToggleButton from '../common/toggleButton-v2/ToggleButton.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() @@ -48,6 +60,8 @@ }: Props = $props() let newToken = $state<string | undefined>(undefined) + let newTokenTestWorkspace = $state<string | undefined>(undefined) + let newTokenTestOpen = $state(false) let newMcpToken = $state<string | undefined>(undefined) let newMcpTokenUrl = $state('') // What an MCP token may do, as the access picker sets it. @@ -55,7 +69,16 @@ let mcpScopes = $state<string[]>(['mcp:all']) // What the user picked; `newTokenExpiration` is that pick held within the ceiling. let pickedExpiration = $state<number | undefined>(undefined) - let newTokenWorkspace = $state<string | undefined>(untrack(() => defaultNewTokenWorkspace)) + // A token is bound to one workspace unless the user picks all of them: a bound token reaches + // only that workspace's routes, none of the instance-level ones. + const initialTokenWorkspace = () => defaultNewTokenWorkspace ?? $operatingWorkspace + let newTokenWorkspace = $state<string | undefined>(untrack(initialTokenWorkspace)) + let newTokenReach = $state<'workspace' | 'all'>( + untrack(initialTokenWorkspace) ? 'workspace' : 'all' + ) + // The owner's admin and superadmin rights are carried only when asked for. + let carryAdmin = $state(false) + let carrySuperAdmin = $state(false) // The workspaces an MCP token reaches. One binds the token to it; several leave it unbound // and are listed in its scopes; all of them leaves it unbound with no list, so it also // reaches the workspaces its owner joins later. @@ -70,6 +93,35 @@ let pickedScopes = $state<string[] | null>(null) let readOnly = $state(false) + let allowedIpsText = $state('') + let allowedIps = $derived( + allowedIpsText + .split(/[\s,]+/) + .map((s) => s.trim()) + .filter((s) => s.length > 0) + ) + // The address this browser calls from, as the server's IP checks resolve it. + let clientIp = $state<string | undefined>(undefined) + let clientIpRequested = false + // While a whole private range is trusted, any host there is believed when it names a client: + // an allowlist then holds only against callers outside the instance's network. + let privateRangesTrusted = $state<boolean | undefined>(undefined) + $effect(() => { + if ($enterpriseLicense && !clientIpRequested) { + clientIpRequested = true + SettingsService.getClientIp() + .then((ip) => (clientIp = ip.trim() || undefined)) + .catch(() => {}) + SettingService.getClientIpTrust() + .then((t) => (privateRangesTrusted = t.private_ranges_trusted)) + .catch(() => {}) + } + }) + function addClientIp() { + if (clientIp && !allowedIps.includes(clientIp)) { + allowedIpsText = [...allowedIps, clientIp].join(', ') + } + } // How this instance lets an MCP client in. `oauth` means it refuses `?token=`, so a // generated token would not get a client in and the URL is handed over bare instead. // A failed read lands on `oauth`: the bare URL works whichever way the setting is, @@ -171,7 +223,8 @@ function exitMcpMode() { mcpCreationMode = false resetExpirationOnModeChange() - newTokenWorkspace = defaultNewTokenWorkspace + newTokenWorkspace = initialTokenWorkspace() + newTokenReach = newTokenWorkspace ? 'workspace' : 'all' newMcpToken = undefined readOnly = false if (mcpLabelAutofilled) { @@ -218,7 +271,10 @@ scopes: tokenScopes, workspace_id: tokenWorkspaceId, read_only: mcpMode ? false : readOnly, - super_admin: mcpMode && mcpSuperAdmin + super_admin: mcpMode ? mcpSuperAdmin : carrySuperAdmin, + admin: carryAdmin, + allowed_ips: + $enterpriseLicense && !mcpMode && allowedIps.length > 0 ? allowedIps : undefined } as NewToken }) @@ -229,6 +285,8 @@ } else { newMcpToken = undefined newToken = `${createdToken}` + newTokenTestWorkspace = tokenWorkspaceId ?? $operatingWorkspace + newTokenTestOpen = false } onTokenCreated(`${createdToken}`) @@ -255,7 +313,14 @@ !mcpAllWorkspaces && mcpWorkspaces.length === 1 ? mcpWorkspaces[0] : undefined ) const mcpReachesWorkspaces = $derived(mcpAllWorkspaces || mcpWorkspaces.length > 0) - const tokenWorkspaceId = $derived(mcpCreationMode ? mcpBoundWorkspace : newTokenWorkspace) + const tokenWorkspaceId = $derived( + mcpCreationMode ? mcpBoundWorkspace : newTokenReach === 'all' ? undefined : newTokenWorkspace + ) + // Offered to who holds admin rights here; the server holds the token within the owner's + // rights in each workspace, so this only hides a switch that would do nothing. + const canCarryAdmin = $derived(!!$userStore?.is_admin || !!$superadmin) + const standardScopes = $derived(scopes ?? pickedScopes ?? undefined) + const tokenWorkspaceItems = $derived(workspaces.map((w) => ({ label: w.name, value: w.id }))) const workspacesScope = $derived( mcpCreationMode && !mcpAllWorkspaces && mcpWorkspaces.length > 1 ? `mcp:workspaces:${mcpWorkspaces.join(',')}` @@ -295,7 +360,7 @@ // The workspace used to browse scripts/flows/endpoints in the scope picker: the first // picked one, or the current one for a token reaching all of them. const scopeWorkspaceId = $derived( - (mcpCreationMode && !mcpAllWorkspaces ? mcpWorkspaces[0] : newTokenWorkspace) || + (mcpCreationMode && !mcpAllWorkspaces ? mcpWorkspaces[0] : tokenWorkspaceId) || $operatingWorkspace || '' ) @@ -339,6 +404,9 @@ bind:access={() => mcpAccess, setMcpAccess} > {#snippet afterAccess()} + {#if canCarryAdmin} + {@render adminToggle(mcpSuperAdmin)} + {/if} {#if $superadmin} <Toggle bind:checked={() => mcpSuperAdmin, setMcpSuperAdmin} @@ -350,6 +418,9 @@ size="xs" /> {/if} + {#if carryAdmin || mcpSuperAdmin} + {@render scopesBoundRights(true, true)} + {/if} {/snippet} </McpAccessPicker> {#if !mcpOnly} @@ -374,6 +445,12 @@ > </div> {/if} + {#if canCarryAdmin && !carryAdmin && !mcpSuperAdmin} + <AdminRelianceNotice + workspaceIds={mcpAllWorkspaces ? undefined : mcpWorkspaces} + scopes={mcpScopes} + /> + {/if} <div class="flex"> <Button onclick={() => createToken(true)} @@ -387,6 +464,46 @@ </div> {/snippet} +{#snippet adminToggle(inSuperadmin: boolean)} + {#if inSuperadmin} + <Toggle + checked + disabled + options={{ + right: 'Workspace admin rights', + rightTooltip: + 'Included in superadmin rights: the token is admin in every workspace it reaches.' + }} + size="xs" + /> + {:else} + <Toggle + bind:checked={carryAdmin} + options={{ + right: 'Workspace admin rights', + rightTooltip: + 'The token carries your admin rights in the workspaces it reaches, within its scopes. Off, it acts as a regular member there.' + }} + size="xs" + /> + {/if} +{/snippet} + +{#snippet scopesBoundRights(scoped: boolean, mcp: boolean)} + <p class="text-2xs text-hint"> + {#if mcp} + Its access above still applies: these rights reach items you are not a member of, only through + the tools that access allows. + {:else if scoped} + Its scopes still apply: these rights reach items you are not a member of, only for what the + scopes allow. They add nothing the scopes leave out. + {:else} + With no scopes, the token can do everything these rights let you do. Pick scopes below to + bound it. + {/if} + </p> +{/snippet} + {#snippet mcpWorkspacePicker()} <div class="flex flex-col gap-1"> {#if mcpAccess === 'selected'} @@ -543,6 +660,97 @@ </div> </div> + {#if !lockWorkspace} + <div class="mt-4 flex flex-col gap-1"> + <span class="text-xs font-semibold text-emphasis">Works in</span> + <div class="flex flex-row flex-wrap items-center gap-2"> + <ToggleButtonGroup bind:selected={newTokenReach} allowEmpty={false}> + {#snippet children({ item })} + <ToggleButton {item} value="workspace" label="One workspace" /> + <ToggleButton {item} value="all" label="All workspaces (instance-wide)" /> + {/snippet} + </ToggleButtonGroup> + {#if newTokenReach === 'workspace'} + <div class="min-w-48"> + <Select + bind:value={newTokenWorkspace} + placeholder="Pick a workspace" + inputClass="w-full" + items={tokenWorkspaceItems} + /> + </div> + {/if} + </div> + <p class="text-2xs text-hint"> + {#if newTokenReach === 'all'} + Works in every workspace you are a member of, and on instance-level endpoints. The CLI + needs this. + {:else} + Works only in this workspace. Other workspaces and instance-level endpoints refuse it. + {/if} + </p> + </div> + {/if} + + {#if canCarryAdmin || $superadmin} + <div class="mt-4 flex flex-col gap-2"> + {#if canCarryAdmin} + {@render adminToggle(carrySuperAdmin)} + {/if} + {#if $superadmin} + <Toggle + bind:checked={carrySuperAdmin} + options={{ + right: 'Superadmin rights', + rightTooltip: + 'The token carries your superadmin rights: admin in every workspace it reaches, including ones you are not a member of. Instance settings also need All workspaces. Off, it acts with your membership in each workspace only.' + }} + size="xs" + /> + {/if} + {#if carryAdmin || carrySuperAdmin} + {@render scopesBoundRights((standardScopes?.length ?? 0) > 0, false)} + {/if} + </div> + {/if} + + {#if $enterpriseLicense} + <div class="mt-4 flex flex-col gap-1"> + <span class="text-xs font-semibold text-emphasis"> + Allowed IPs <span class="font-normal text-secondary">(optional)</span> + </span> + <TextInput + inputProps={{ type: 'text', placeholder: '203.0.113.4, 10.0.0.0/8' }} + bind:value={allowedIpsText} + class="w-full" + /> + <p class="text-2xs text-hint"> + IP addresses or CIDR ranges, separated by commas. Requests from any other address are + refused. Leave empty to allow any. + </p> + {#if privateRangesTrusted && allowedIps.length > 0} + <Alert type="warning" size="xs" title="Insiders can claim an allowed address"> + This instance trusts a whole private range as proxies, so a host on its private network, + a job included, can name its own client address. The allowlist holds against callers + outside that network only. An instance admin can list the reverse proxies on the Client + IP instance settings page. + </Alert> + {/if} + {#if clientIp} + <div class="flex items-center gap-2 text-2xs text-secondary"> + <span>Windmill sees this browser's IP as <code>{clientIp}</code></span> + {#if !allowedIps.includes(clientIp)} + <Button variant="subtle" unifiedSize="2xs" onclick={addClientIp}>Add</Button> + {/if} + </div> + {/if} + </div> + {:else} + <p class="mt-4 text-2xs text-hint"> + Restricting a token to IP ranges requires Enterprise Edition. + </p> + {/if} + {#if !scopes || scopes.length === 0} <div class="mt-4"> <ScopesPicker @@ -554,6 +762,16 @@ </div> {/if} + {#if canCarryAdmin && !carryAdmin && !carrySuperAdmin} + <div class="mt-4"> + <AdminRelianceNotice + workspaceIds={tokenWorkspaceId ? [tokenWorkspaceId] : undefined} + scopes={standardScopes} + {readOnly} + /> + </div> + {/if} + <div class="mt-4 flex justify-end gap-2 flex-row"> {#if !mcpOnly} <Button @@ -565,13 +783,24 @@ Cancel </Button> {/if} - <Button on:click={() => createToken()} variant="accent">New token</Button> + <Button + on:click={() => createToken()} + disabled={!lockWorkspace && newTokenReach === 'workspace' && !newTokenWorkspace} + variant="accent">New token</Button + > </div> {/if} </div> {#if newToken && displayCreateToken} <TokenDisplay token={newToken} /> + <div class="-mt-4 mb-6"> + <CollapseLink text="Check what this token can do" bind:open={newTokenTestOpen}> + {#key newToken} + <TokenInspector token={newToken} workspace={newTokenTestWorkspace} /> + {/key} + </CollapseLink> + </div> {/if} {#if newMcpToken && displayCreateToken} diff --git a/frontend/src/lib/components/settings/EditTokenScopesModal.svelte b/frontend/src/lib/components/settings/EditTokenScopesModal.svelte index 0847724740..a892501b84 100644 --- a/frontend/src/lib/components/settings/EditTokenScopesModal.svelte +++ b/frontend/src/lib/components/settings/EditTokenScopesModal.svelte @@ -12,7 +12,9 @@ mcpAccessOf } from '../mcp/McpAccessPicker.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' - import { usersWorkspaceStore } from '$lib/stores' + import { enterpriseLicense, usersWorkspaceStore } from '$lib/stores' + import Select from '../select/Select.svelte' + import { displayDate } from '$lib/utils' const operatingWorkspace = useOperatingWorkspace() @@ -20,10 +22,13 @@ open: boolean tokenPrefix?: string initialLabel?: string - /** When false, the label is shown read-only (system tokens — see `isUserToken`). */ + /** When false, the label, expiration and allowed IPs are read-only (system tokens — see + * `isUserToken`). */ labelEditable?: boolean initialScopes?: string[] tokenWorkspaceId?: string + initialExpiration?: string + initialAllowedIps?: string[] onSaved?: () => void } @@ -34,9 +39,32 @@ labelEditable = true, initialScopes, tokenWorkspaceId, + initialExpiration, + initialAllowedIps, onSaved }: Props = $props() + const DAY_SECS = 24 * 60 * 60 + type ExpirationChoice = 'keep' | 'never' | number + const expirationItems: { label: string; value: ExpirationChoice }[] = [ + { label: 'Keep current', value: 'keep' }, + { label: '1 hour from now', value: 60 * 60 }, + { label: '1 day from now', value: DAY_SECS }, + { label: '7 days from now', value: 7 * DAY_SECS }, + { label: '30 days from now', value: 30 * DAY_SECS }, + { label: '90 days from now', value: 90 * DAY_SECS }, + { label: '180 days from now', value: 180 * DAY_SECS }, + { label: '365 days from now', value: 365 * DAY_SECS }, + { label: 'Never', value: 'never' } + ] + let expirationChoice = $state<ExpirationChoice>('keep') + let allowedIpsText = $state('') + const parseIps = (text: string) => + text + .split(/[\s,]+/) + .map((s) => s.trim()) + .filter((s) => s.length > 0) + // Treat as MCP only when *all* existing scopes are mcp:* — mixed-scope or // null-scope tokens fall back to the standard picker so non-MCP scopes are // never silently dropped. @@ -99,6 +127,8 @@ untrack(() => { labelValue = initialLabel ?? '' mcpTouched = false + expirationChoice = 'keep' + allowedIpsText = (initialAllowedIps ?? []).join(', ') }) } }) @@ -131,7 +161,22 @@ requestBody: { scopes: scopesToSave } }) } - if (labelChanged || scopesChanged) { + const limits: { expiration?: string | null; allowed_ips?: string[] | null } = {} + if (labelEditable && expirationChoice !== 'keep') { + limits.expiration = + expirationChoice === 'never' + ? null + : new Date(Date.now() + expirationChoice * 1000).toISOString() + } + const ips = parseIps(allowedIpsText) + if (labelEditable && $enterpriseLicense && !scopesEqual(ips, initialAllowedIps ?? [])) { + limits.allowed_ips = ips.length > 0 ? ips : null + } + const limitsChanged = Object.keys(limits).length > 0 + if (limitsChanged) { + await UserService.updateTokenLimits({ tokenPrefix, requestBody: limits }) + } + if (labelChanged || scopesChanged || limitsChanged) { sendUserToast('Token updated') } onSaved?.() @@ -164,6 +209,33 @@ {/if} </div> + {#if labelEditable} + <div class="flex flex-col gap-1"> + <span class="text-xs font-semibold text-emphasis">Expiration</span> + <span class="text-2xs text-secondary"> + Currently {initialExpiration ? displayDate(initialExpiration) : 'never expires'} + </span> + <Select bind:value={expirationChoice} inputClass="w-full" items={expirationItems} /> + <p class="text-2xs text-hint"> + A later expiration is shortened to this instance's maximum token lifetime, if it has one. + </p> + </div> + + {#if $enterpriseLicense} + <div class="flex flex-col gap-1"> + <span class="text-xs font-semibold text-emphasis">Allowed IPs</span> + <TextInput + inputProps={{ type: 'text', placeholder: '203.0.113.4, 10.0.0.0/8' }} + bind:value={allowedIpsText} + class="w-full" + /> + <p class="text-2xs text-hint"> + IP addresses or CIDR ranges, separated by commas. Leave empty to allow any. + </p> + </div> + {/if} + {/if} + <div class="flex flex-col gap-1"> {#if !isMcp} <span class="text-xs font-semibold text-emphasis">Scopes</span> diff --git a/frontend/src/lib/components/settings/ScopesPicker.svelte b/frontend/src/lib/components/settings/ScopesPicker.svelte index c4a8026d14..5532783205 100644 --- a/frontend/src/lib/components/settings/ScopesPicker.svelte +++ b/frontend/src/lib/components/settings/ScopesPicker.svelte @@ -12,7 +12,7 @@ value: string[] | null /** Read-only flag; also forwarded to McpScopeSelector to filter incompatible * endpoints/runnables. Two-way bound so the inline toggle below the - * "Limit token permissions" switch (and the MCP variant) writes back. */ + * "Restrict to specific scopes" switch (and the MCP variant) writes back. */ readOnly?: boolean } @@ -63,12 +63,17 @@ <Toggle bind:checked={limited} options={{ - right: 'Limit token permissions', + right: 'Restrict to specific scopes', rightTooltip: - 'When off, the token has full API access. Turn on to restrict it to specific scopes.' + 'When off, the token can call any endpoint its rights allow. Turn on to allow only the scopes you pick: this narrows what the token can do, never widens it.' }} size="xs" /> + {#if limited && standardScopes.length === 0} + <p class="text-2xs text-yellow-600 dark:text-yellow-400"> + Pick at least one scope: with none picked, the token is not restricted. + </p> + {/if} {#if limited} <ScopeSelector bind:selectedScopes={standardScopes} workspaceId={workspaceId || undefined}> {#snippet topSlot()} diff --git a/frontend/src/lib/components/settings/TokenInspector.svelte b/frontend/src/lib/components/settings/TokenInspector.svelte new file mode 100644 index 0000000000..f8f9b1716d --- /dev/null +++ b/frontend/src/lib/components/settings/TokenInspector.svelte @@ -0,0 +1,258 @@ +<script lang="ts"> + import { untrack } from 'svelte' + import { OpenAPI, type TokenIntrospection } from '$lib/gen' + import { displayDate } from '$lib/utils' + import { Alert, Badge, Button } from '../common' + import TextInput from '../text_input/TextInput.svelte' + import Select from '../select/Select.svelte' + import { Check, ShieldCheck, X } from 'lucide-svelte' + import { userStore } from '$lib/stores' + import AdminRelianceNotice from './AdminRelianceNotice.svelte' + + interface Props { + /** The token to inspect. When unset, the user pastes one. */ + token?: string + /** Workspace the identity and the route are evaluated in. */ + workspace?: string + /** Route to check, relative to `/api/w/{workspace}/`, or a full `/api/...` path. */ + defaultPath?: string + defaultMethod?: string + } + + let { token, workspace, defaultPath, defaultMethod }: Props = $props() + + let pastedToken = $state('') + let effectiveToken = $derived((token ?? pastedToken).trim()) + let routeMethod = $state(untrack(() => defaultMethod ?? 'GET')) + let routePath = $state(untrack(() => defaultPath ?? '')) + let result = $state<TokenIntrospection | undefined>(undefined) + let error = $state<string | undefined>(undefined) + let loading = $state(false) + + const methods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].map((m) => ({ label: m, value: m })) + + const kindLabel: Record<TokenIntrospection['kind'], string> = { + session: 'Browser session', + api_token: 'API token', + jwt: 'Signed token (JWT)', + external: 'External issuer', + superadmin_secret: 'Superadmin secret' + } + + async function inspect() { + if (!effectiveToken) return + loading = true + error = undefined + result = undefined + try { + const params = new URLSearchParams() + if (workspace) params.set('workspace', workspace) + if (routePath.trim()) { + params.set('path', routePath.trim()) + params.set('method', routeMethod) + } + // The route describes only the credential presenting the request, so the token + // must be the bearer credential, not a parameter. + const response = await fetch(`${OpenAPI.BASE}/tokens/introspect?${params}`, { + headers: { Authorization: `Bearer ${effectiveToken}` }, + credentials: 'omit' + }) + if (response.status === 401) { + error = 'This token is not valid: it does not exist, has expired or was revoked.' + } else if (!response.ok) { + error = (await response.text()) || `Request failed (${response.status})` + } else { + result = await response.json() + } + } catch (e) { + error = e instanceof Error ? e.message : String(e) + } finally { + loading = false + } + } + + /** Whether the server read the token's expiry and workspace bounds: it does for its own rows + * and signed tokens, not for an external issuer's or a guest's, whose absence means nothing. */ + function metadataKnown(r: TokenIntrospection): boolean { + return r.kind === 'api_token' || r.kind === 'session' || r.expiration != undefined + } + + function expiryText(expiration: string | undefined): string { + return expiration ? displayDate(expiration) : 'Never' + } +</script> + +<div class="flex flex-col gap-3"> + {#if token === undefined} + <div class="flex flex-col gap-1"> + <span class="text-xs text-emphasis font-semibold">Token</span> + <TextInput + bind:value={pastedToken} + inputProps={{ type: 'password', placeholder: 'Paste a token to test', autocomplete: 'off' }} + class="w-full" + /> + </div> + {/if} + <div class="flex flex-col gap-1"> + <span class="text-xs text-emphasis font-semibold"> + Route to check <span class="text-hint font-normal">(optional)</span> + </span> + <div class="flex gap-2 items-center"> + <div class="w-28 shrink-0"> + <Select items={methods} bind:value={routeMethod} size="sm" /> + </div> + <TextInput + bind:value={routePath} + inputProps={{ + placeholder: workspace + ? 'scripts/list, or a full /api/... path' + : '/api/w/<workspace>/...' + }} + size="sm" + class="w-full" + /> + <Button + variant="accent-secondary" + unifiedSize="sm" + startIcon={{ icon: ShieldCheck }} + disabled={!effectiveToken} + {loading} + onClick={inspect} + > + Test token + </Button> + </div> + </div> + + {#if error} + <Alert type="error" title="Could not test the token" size="xs">{error}</Alert> + {/if} + + {#if result} + <div class="flex flex-col gap-3 border rounded-md p-3 bg-surface-tertiary text-xs"> + <div class="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1.5"> + <span class="text-secondary">Kind</span> + <span class="text-primary">{kindLabel[result.kind] ?? result.kind}</span> + <span class="text-secondary">Acts as</span> + <span class="text-primary">{result.email} ({result.username})</span> + {#if result.label} + <span class="text-secondary">Label</span> + <span class="text-primary">{result.label}</span> + {/if} + {#if result.token_prefix} + <span class="text-secondary">Prefix</span> + <span class="text-primary">{result.token_prefix}****</span> + {/if} + <span class="text-secondary">Expires</span> + <span class="text-primary"> + {metadataKnown(result) ? expiryText(result.expiration) : 'Not reported'} + </span> + <span class="text-secondary">Workspaces</span> + <span class="text-primary"> + {#if result.workspace_ids?.length} + {result.workspace_ids.join(', ')} + {:else if result.workspace_id} + {result.workspace_id} + {:else if metadataKnown(result)} + Every workspace the owner is a member of + {:else} + Not reported + {/if} + </span> + <span class="text-secondary">Rights</span> + <div class="flex flex-wrap gap-1"> + {#if result.super_admin} + <Badge color="red" small>Superadmin</Badge> + {/if} + {#if result.admin_withheld} + <Badge color="gray" small>Admin rights withheld</Badge> + {/if} + {#if result.read_only} + <Badge color="blue" small>Read-only</Badge> + {/if} + {#if result.job_id} + <Badge color="gray" small>Job {result.job_id}</Badge> + {/if} + {#if !result.super_admin && !result.admin_withheld && !result.read_only && !result.job_id} + <span class="text-primary">Owner's member rights</span> + {/if} + </div> + {#if result.allowed_ips?.length} + <span class="text-secondary">Usable from</span> + <span class="text-primary">{result.allowed_ips.join(', ')}</span> + {/if} + <span class="text-secondary">Scopes</span> + <div class="flex flex-wrap gap-1"> + {#if result.scopes} + {#each result.scopes as scope (scope)} + <Badge color="gray" small>{scope}</Badge> + {:else} + <span class="text-primary">None</span> + {/each} + {:else} + <span class="text-primary">Unrestricted</span> + {/if} + </div> + </div> + + {#if result.admin_withheld && !result.super_admin && !result.job_id && result.email === $userStore?.email} + <AdminRelianceNotice + workspaceIds={result.workspace_ids ?? + (result.workspace_id ? [result.workspace_id] : undefined)} + scopes={result.scopes ?? undefined} + readOnly={result.read_only} + /> + {/if} + + {#if result.workspace} + {@const ws = result.workspace} + <div class="border-t pt-3 grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1.5"> + <span class="text-secondary">In {ws.workspace_id}</span> + {#if ws.usable} + <div class="flex flex-wrap gap-1"> + <Badge color={ws.is_admin ? 'indigo' : ws.is_operator ? 'yellow' : 'green'} small> + {ws.is_admin ? 'Admin' : ws.is_operator ? 'Restricted role' : 'Member'} + </Badge> + </div> + <span class="text-secondary">Groups</span> + <span class="text-primary">{ws.groups?.join(', ') || 'None'}</span> + <span class="text-secondary">Folders</span> + <span class="text-primary"> + {#if ws.folders?.length} + {ws.folders + .map((f) => `${f.name} (${f.owner ? 'owner' : f.write ? 'write' : 'read'})`) + .join(', ')} + {:else} + None + {/if} + </span> + {:else} + <span class="text-primary">Not usable in this workspace</span> + {/if} + </div> + {/if} + + {#if result.route} + {@const route = result.route} + <div class="border-t pt-3 flex flex-col gap-1"> + <div class="flex items-start gap-2"> + {#if route.allowed} + <Check size={14} class="shrink-0 mt-0.5 text-green-600 dark:text-green-400" /> + {:else} + <X size={14} class="shrink-0 mt-0.5 text-red-600 dark:text-red-400" /> + {/if} + <span class="text-primary font-mono break-all">{route.method} {route.path}</span> + </div> + {#if route.allowed} + <span class="text-secondary"> + The token passes the route checks. The endpoint can still refuse it: a scope that + names a path is matched against the item, and the identity needs permission on it. + </span> + {:else} + <span class="text-secondary">{route.reason}</span> + {/if} + </div> + {/if} + </div> + {/if} +</div> diff --git a/frontend/src/lib/components/settings/TokensTable.svelte b/frontend/src/lib/components/settings/TokensTable.svelte index 3cd83e7d89..a2777591d8 100644 --- a/frontend/src/lib/components/settings/TokensTable.svelte +++ b/frontend/src/lib/components/settings/TokensTable.svelte @@ -2,7 +2,10 @@ import { untrack } from 'svelte' import TableCustom from '$lib/components/TableCustom.svelte' import { displayDate } from '$lib/utils' - import { UserService, type TruncatedToken } from '$lib/gen' + import { enterpriseLicense, workspaceStore } from '$lib/stores' + import CollapseLink from '../CollapseLink.svelte' + import TokenInspector from './TokenInspector.svelte' + import { UserService, type TokenRisk, type TokenRiskCounts, type TruncatedToken } from '$lib/gen' import { sendUserToast } from '$lib/toast' import CreateToken from './CreateToken.svelte' import EditTokenScopesModal from './EditTokenScopesModal.svelte' @@ -11,25 +14,17 @@ import Alert from '../common/alert/Alert.svelte' import { Pen, Trash } from 'lucide-svelte' import { MCP_SESSION } from '../mcp/McpAccessPicker.svelte' + import { tokenRiskSummary, TOKEN_RISK_INFO } from './tokenRisks' // --- Props --- interface Props { - showMcpMode?: boolean - openWithMcpMode?: boolean defaultNewTokenLabel?: string defaultNewTokenWorkspace?: string scopes?: string[] onTokenCreated: (token: string) => void } - let { - showMcpMode = false, - openWithMcpMode = false, - defaultNewTokenLabel, - defaultNewTokenWorkspace, - scopes, - onTokenCreated - }: Props = $props() + let { defaultNewTokenLabel, defaultNewTokenWorkspace, scopes, onTokenCreated }: Props = $props() // --- Local State --- let tokens = $state<TruncatedToken[]>([]) @@ -41,10 +36,13 @@ label: string | undefined scopes: string[] | undefined workspaceId: string | undefined + expiration: string | undefined + allowedIps: string[] | undefined } | undefined >(undefined) let editModalOpen = $state(false) + let testOpen = $state(false) $effect(() => { listTokens() @@ -104,6 +102,15 @@ }).length ) + // Over all the user's tokens, not only the page shown. + let riskCounts: TokenRiskCounts | undefined = $state(undefined) + let riskSummary = $derived(tokenRiskSummary(riskCounts)) + + // The access column already shows a token's workspace and rights. + function rowBadgeRisks(risks: TokenRisk[]): TokenRisk[] { + return risks.filter((r) => r === 'never_expires' || r === 'unused') + } + function handleTokenCreated(token: string) { onTokenCreated(token) listTokens() @@ -123,23 +130,26 @@ tokenPrefix: string, tokenLabel: string | undefined, tokenScopes: string[] | undefined, - tokenWorkspaceId: string | undefined + tokenWorkspaceId: string | undefined, + tokenExpiration: string | undefined, + tokenAllowedIps: string[] | undefined ) { editingToken = { prefix: tokenPrefix, label: tokenLabel, scopes: tokenScopes, - workspaceId: tokenWorkspaceId + workspaceId: tokenWorkspaceId, + expiration: tokenExpiration, + allowedIps: tokenAllowedIps } editModalOpen = true } export async function listTokens(): Promise<void> { - tokens = await UserService.listTokens({ - excludeEphemeral: true, - page: tokenPage, - perPage: 100 - }) + ;[tokens, riskCounts] = await Promise.all([ + UserService.listTokens({ excludeEphemeral: true, page: tokenPage, perPage: 100 }), + UserService.getTokenRiskCounts() + ]) } function handleNextPage() { @@ -153,11 +163,24 @@ } </script> -<div class="flex flex-col p-4 border border-border-light rounded-md"> - <h2 class="text-emphasis text-sm font-semibold mb-1">Tokens</h2> +<div class="flex flex-col"> <div class="text-xs text-secondary mb-2"> Authenticate to the Windmill API with access tokens. </div> + {#if riskSummary.length > 0} + <div class="mb-2"> + <Alert type="warning" title="Some of your tokens need a review" size="xs"> + <ul class="list-disc pl-4"> + {#each riskSummary as line (line)} + <li>{line}</li> + {/each} + </ul> + A leaked token keeps working until it expires or is deleted. Delete tokens you no longer use, + and give the ones you keep an expiration, the narrowest scopes they need and no admin rights + unless they require them. + </Alert> + </div> + {/if} {#if expiringSoonCount > 0} <div class="mb-2"> <Alert @@ -168,8 +191,6 @@ </div> {/if} <CreateToken - {showMcpMode} - {openWithMcpMode} bind:newTokenLabel {defaultNewTokenWorkspace} {scopes} @@ -182,6 +203,7 @@ <th>Prefix</th> <th>Label</th> <th>Expiration</th> + <th>Access</th> <th>Scopes</th> <th></th> </tr> @@ -189,11 +211,25 @@ {#snippet body()} <tbody> {#if tokens && tokens.length > 0} - {#each tokens as { token_prefix, expiration, label, scopes, workspace_id, read_only } (token_prefix)} + {#each tokens as { token_prefix, expiration, label, scopes, workspace_id, read_only, allowed_ips, admin, super_admin, risks } (token_prefix)} + {@const rowRisks = rowBadgeRisks(risks)} {@const badge = expirationBadge(expiration, label)} <tr> <td class="w-32 text-xs text-primary">{token_prefix}****</td> - <td class="min-w-0 max-w-32 truncate text-xs text-primary">{label ?? ''}</td> + <td class="min-w-0 max-w-40 text-xs text-primary"> + <div class="truncate">{label ?? ''}</div> + {#if rowRisks.length > 0} + <div class="flex flex-wrap gap-1 mt-0.5"> + {#each rowRisks as risk (risk)} + <span title={TOKEN_RISK_INFO[risk].tooltip}> + <Badge color={TOKEN_RISK_INFO[risk].color} small> + {TOKEN_RISK_INFO[risk].badge} + </Badge> + </span> + {/each} + </div> + {/if} + </td> <td class="w-40 whitespace-nowrap text-xs text-secondary"> <div class="flex items-center gap-1.5"> {displayDate(expiration ?? '')} @@ -202,6 +238,22 @@ {/if} </div> </td> + <td class="whitespace-nowrap text-xs text-secondary"> + <div class="flex items-center gap-1.5"> + <span + title={workspace_id + ? `Usable only in workspace ${workspace_id}` + : 'Usable in every workspace you are a member of'} + > + {workspace_id ?? 'All workspaces'} + </span> + {#if super_admin} + <Badge color="red" small>Superadmin</Badge> + {:else if admin} + <Badge color="indigo" small>Admin</Badge> + {/if} + </div> + </td> <td class="min-w-0 max-w-48 truncate text-xs text-secondary" title={shownScopes(scopes)} @@ -210,6 +262,15 @@ {#if read_only} <Badge color="blue" small>Read-only</Badge> {/if} + {#if $enterpriseLicense && allowed_ips && allowed_ips.length > 0} + <span title="Usable only from {allowed_ips.join(', ')}"> + <Badge color="gray" small> + {allowed_ips.length === 1 + ? allowed_ips[0] + : `${allowed_ips.length} IP ranges`} + </Badge> + </span> + {/if} <span class="truncate">{shownScopes(scopes)}</span> </div> </td> @@ -223,7 +284,9 @@ token_prefix, label ?? undefined, scopes ?? undefined, - workspace_id ?? undefined + workspace_id ?? undefined, + expiration ?? undefined, + allowed_ips ?? undefined )} size="xs" startIcon={{ icon: Pen }} @@ -260,6 +323,16 @@ {/if} </div> </div> + <div class="mt-4"> + <CollapseLink text="Test a token" bind:open={testOpen}> + <div class="text-xs text-secondary mb-2"> + See who a token acts as, what it is scoped to and whether it can call a route{$workspaceStore + ? ` in ${$workspaceStore}` + : ''}. + </div> + <TokenInspector workspace={$workspaceStore} /> + </CollapseLink> + </div> </div> <EditTokenScopesModal @@ -269,5 +342,7 @@ labelEditable={isUserToken(editingToken?.label)} initialScopes={editingToken?.scopes} tokenWorkspaceId={editingToken?.workspaceId} + initialExpiration={editingToken?.expiration} + initialAllowedIps={editingToken?.allowedIps} onSaved={listTokens} /> diff --git a/frontend/src/lib/components/settings/TotpAuthenticator.svelte b/frontend/src/lib/components/settings/TotpAuthenticator.svelte new file mode 100644 index 0000000000..f0bb87f01e --- /dev/null +++ b/frontend/src/lib/components/settings/TotpAuthenticator.svelte @@ -0,0 +1,28 @@ +<script lang="ts"> + import { CopyButton } from '$lib/components/common' + import { renderSVG } from 'uqr' + + interface Props { + setup: { secret: string; otpauth_url: string } + } + + let { setup }: Props = $props() +</script> + +<div class="flex flex-col gap-1"> + <span class="text-xs text-secondary font-normal"> + Scan this QR code with an authenticator app, or open it on this device. + </span> + <a + href={setup.otpauth_url} + aria-label="Add to an authenticator app" + class="w-40 h-40 bg-white p-1 rounded-md" + > + {@html renderSVG(setup.otpauth_url)} + </a> + <div class="flex flex-row flex-wrap gap-1 items-center text-2xs text-secondary font-normal"> + Or enter this key manually: + <span class="font-mono text-emphasis break-all">{setup.secret}</span> + <CopyButton value={setup.secret} /> + </div> +</div> diff --git a/frontend/src/lib/components/settings/TotpModal.svelte b/frontend/src/lib/components/settings/TotpModal.svelte new file mode 100644 index 0000000000..0009074c8a --- /dev/null +++ b/frontend/src/lib/components/settings/TotpModal.svelte @@ -0,0 +1,162 @@ +<script module lang="ts"> + export type TotpAction = 'setup' | 'recovery_codes' | 'disable' +</script> + +<script lang="ts"> + import { UserService } from '$lib/gen' + import { Alert, Button } from '$lib/components/common' + import Modal from '../common/modal/Modal.svelte' + import Stepper from '../common/stepper/Stepper.svelte' + import TextInput from '../text_input/TextInput.svelte' + import { sendUserToast } from '$lib/toast' + import TotpAuthenticator from './TotpAuthenticator.svelte' + import TotpRecoveryCodes from './TotpRecoveryCodes.svelte' + + interface Props { + action: TotpAction | undefined + onClose: () => void + } + + let { action = $bindable(), onClose }: Props = $props() + + const SETUP_STEPS = ['Password', 'Authenticator', 'Recovery codes'] + + let step = $state(0) + let password = $state('') + let code = $state('') + let setup = $state<{ secret: string; otpauth_url: string } | undefined>(undefined) + let recoveryCodes = $state<string[] | undefined>(undefined) + let saved = $state(false) + let busy = $state(false) + + const title = $derived( + action == 'setup' + ? 'Set up two-factor authentication' + : action == 'recovery_codes' + ? 'New recovery codes' + : 'Turn off two-factor authentication' + ) + + // Closing at any step drops the secret and the codes from the page. + function close() { + step = 0 + password = '' + code = '' + setup = undefined + recoveryCodes = undefined + saved = false + action = undefined + onClose() + } + + const canContinue = $derived( + recoveryCodes ? saved : action == 'setup' && step == 0 ? !!password : !!code + ) + + async function next() { + if (!canContinue || busy) return + busy = true + try { + if (recoveryCodes) { + close() + } else if (action == 'setup' && step == 0) { + setup = await UserService.setupTotp({ requestBody: { password } }) + password = '' + step = 1 + } else if (action == 'disable') { + sendUserToast(await UserService.disableTotp({ requestBody: { code } })) + close() + } else { + const requestBody = { code } + recoveryCodes = ( + action == 'setup' + ? await UserService.enableTotp({ requestBody }) + : await UserService.regenerateTotpRecoveryCodes({ requestBody }) + ).recovery_codes + setup = undefined + code = '' + step = 2 + } + } finally { + busy = false + } + } + + const nextLabel = $derived( + recoveryCodes + ? 'Done' + : action == 'setup' + ? step == 0 + ? 'Continue' + : 'Turn on' + : action == 'disable' + ? 'Turn off' + : 'Create new codes' + ) +</script> + +{#snippet primary()} + <Button + unifiedSize="sm" + variant="accent" + destructive={action == 'disable'} + disabled={!canContinue} + loading={busy} + onClick={next} + > + {nextLabel} + </Button> +{/snippet} + +<Modal + {title} + bind:open={() => action != undefined, (v) => !v && action != undefined && close()} + on:confirmed={next} + kind={recoveryCodes ? 'X' : 'button'} +> + <div class="flex flex-col gap-4"> + {#if action == 'setup'} + <Stepper tabs={SETUP_STEPS} selectedIndex={step} maxReachedIndex={step} small /> + {/if} + + {#if recoveryCodes} + {#if action == 'setup'} + <Alert type="success" title="Two-factor authentication is on" size="xs"> + Logging in with your password now also asks for a code from your authenticator app. + </Alert> + {/if} + <TotpRecoveryCodes codes={recoveryCodes} bind:saved /> + <div class="flex justify-end"> + {@render primary()} + </div> + {:else if action == 'setup' && step == 0} + <label class="flex flex-col gap-1"> + <span class="text-xs text-emphasis font-semibold">Password</span> + <span class="text-xs text-secondary font-normal"> + Confirm it's you before adding an authenticator to this account. + </span> + <TextInput + inputProps={{ type: 'password', autocomplete: 'current-password' }} + bind:value={password} + /> + </label> + {:else} + {#if setup} + <TotpAuthenticator {setup} /> + {/if} + <label class="flex flex-col gap-1"> + <span class="text-xs text-emphasis font-semibold">Code</span> + <span class="text-xs text-secondary font-normal"> + {setup + ? 'The 6-digit code your authenticator app shows' + : 'A code from your authenticator app, or one of your recovery codes'} + </span> + <TextInput inputProps={{ autocomplete: 'one-time-code', name: 'totp' }} bind:value={code} /> + </label> + {/if} + </div> + + {#snippet actions()} + {@render primary()} + {/snippet} +</Modal> diff --git a/frontend/src/lib/components/settings/TotpRecoveryCodes.svelte b/frontend/src/lib/components/settings/TotpRecoveryCodes.svelte new file mode 100644 index 0000000000..6504c3743e --- /dev/null +++ b/frontend/src/lib/components/settings/TotpRecoveryCodes.svelte @@ -0,0 +1,37 @@ +<script lang="ts"> + import { Alert, Button } from '$lib/components/common' + import Checkbox from '../common/checkbox/Checkbox.svelte' + import CopyableCodeBlock from '../details/CopyableCodeBlock.svelte' + import { plaintext } from 'svelte-highlight/languages' + import { download } from '$lib/utils' + + interface Props { + codes: string[] + saved: boolean + } + + let { codes, saved = $bindable() }: Props = $props() +</script> + +<div class="flex flex-col gap-1"> + <span class="text-xs text-secondary font-normal"> + Each code logs you in once if you lose your authenticator. + </span> + <CopyableCodeBlock code={codes.join('\n')} language={plaintext} /> + <div class="flex"> + <Button + unifiedSize="sm" + variant="default" + onClick={() => download('windmill-recovery-codes.txt', codes.join('\n'))} + > + Download + </Button> + </div> +</div> +<Alert type="warning" title="Save these codes now" size="xs"> + They are shown only once. Keep them somewhere other than this device. +</Alert> +<label class="flex flex-row gap-2 items-center text-xs text-primary font-normal"> + <Checkbox checked={saved} onChange={() => (saved = !saved)} /> + I saved my recovery codes +</label> diff --git a/frontend/src/lib/components/settings/UserInfoSettings.svelte b/frontend/src/lib/components/settings/UserInfoSettings.svelte index 72ebfdc789..ae7452d9f8 100644 --- a/frontend/src/lib/components/settings/UserInfoSettings.svelte +++ b/frontend/src/lib/components/settings/UserInfoSettings.svelte @@ -5,6 +5,7 @@ import { Button } from '$lib/components/common' import { sendUserToast } from '$lib/toast' import TextInput from '../text_input/TextInput.svelte' + import TotpModal, { type TotpAction } from './TotpModal.svelte' let newPassword = $state<string | undefined>(undefined) let passwordError = $state<string | undefined>(undefined) @@ -19,11 +20,23 @@ async function loadLoginType(): Promise<void> { login_type = (await UserService.globalWhoami()).login_type + if (login_type == 'password') await loadTotp() if (login_type == 'pending_oauth') { passwordAllowed = !(await UserService.isPasswordLoginDisabled().catch(() => false)) } } + let totpEnabled = $state<boolean | undefined>(undefined) + let totpRequired = $state(false) + let totpAction = $state<TotpAction | undefined>(undefined) + + async function loadTotp(): Promise<void> { + // Builds without two-factor support do not serve the route: the section stays hidden. + const status = await UserService.getTotpStatus().catch(() => undefined) + totpEnabled = status?.enabled + totpRequired = status?.required ?? false + } + async function setPassword(): Promise<void> { if (newPassword) { await UserService.setPassword({ @@ -42,41 +55,74 @@ } </script> -<div class="border border-border-light rounded-md p-4 h-full"> - <h2 class="text-emphasis text-sm font-semibold mb-2">User info</h2> - - <form class="flex flex-col gap-6"> - <div class="w-full text-primary flex flex-col gap-1"> - <div class="text-xs text-emphasis font-semibold">Email</div> - <span class="text-xs font-normal text-primary"> - {$usersWorkspaceStore?.email} - </span> - </div> +<form class="flex flex-col gap-6"> + <div class="w-full text-primary flex flex-col gap-1"> + <div class="text-xs text-emphasis font-semibold">Email</div> + <span class="text-xs font-normal text-primary"> + {$usersWorkspaceStore?.email} + </span> + </div> + {#if login_type == 'password' || (login_type == 'pending_oauth' && passwordAllowed)} <label class="flex flex-col gap-1 w-120"> <span class="text-xs text-emphasis font-semibold">Password</span> - {#if login_type == 'password' || (login_type == 'pending_oauth' && passwordAllowed)} - <div class="flex flex-row gap-1 items-center"> - <TextInput - inputProps={{ autocomplete: 'new-password', type: 'password' }} - bind:value={newPassword} - error={passwordError} - /> - <Button - size="sm" - variant="default" - btnClasses="w-min whitespace-nowrap" - on:click={setPassword}>Set password</Button - > - </div> - {#if passwordError} - <div class="text-red-600 text-2xs">{passwordError}</div> - {/if} - {:else if login_type == 'github'} - <span class="text-xs text-primary font-normal" - >Authenticated through Github OAuth2. Cannot set a password.</span + <div class="flex flex-row gap-1 items-center"> + <TextInput + inputProps={{ autocomplete: 'new-password', type: 'password' }} + bind:value={newPassword} + error={passwordError} + /> + <Button + size="sm" + variant="default" + btnClasses="w-min whitespace-nowrap" + on:click={setPassword}>Set password</Button > + </div> + {#if passwordError} + <div class="text-red-600 text-2xs">{passwordError}</div> {/if} </label> - </form> -</div> + {:else if !['none', 'pending_oauth', 'service_account'].includes(login_type)} + <div class="flex flex-col gap-1"> + <div class="text-xs text-emphasis font-semibold">Sign-in</div> + <span class="text-xs font-normal text-primary"> + Through <span class="capitalize">{login_type}</span> single sign-on + </span> + </div> + {/if} + + {#if login_type == 'password' && totpEnabled != undefined} + <div class="flex flex-col gap-1 w-120"> + <span class="text-xs text-emphasis font-semibold">Two-factor authentication</span> + <span class="text-xs text-secondary font-normal"> + {totpEnabled + ? totpRequired + ? 'On, as this instance requires. Logging in with your password also asks for a code from your authenticator app.' + : 'On. Logging in with your password also asks for a code from your authenticator app.' + : 'Ask for a code from an authenticator app each time you log in with your password.'} + </span> + <div class="flex flex-row gap-1"> + {#if totpEnabled} + <Button + unifiedSize="sm" + variant="default" + onClick={() => (totpAction = 'recovery_codes')} + > + New recovery codes + </Button> + {#if !totpRequired} + <Button unifiedSize="sm" variant="default" onClick={() => (totpAction = 'disable')}> + Turn off + </Button> + {/if} + {:else} + <Button unifiedSize="sm" variant="default" onClick={() => (totpAction = 'setup')}> + Set up two-factor authentication + </Button> + {/if} + </div> + </div> + {/if} +</form> +<TotpModal bind:action={totpAction} onClose={loadTotp} /> diff --git a/frontend/src/lib/components/settings/tokenRisks.ts b/frontend/src/lib/components/settings/tokenRisks.ts new file mode 100644 index 0000000000..7eb18b866d --- /dev/null +++ b/frontend/src/lib/components/settings/tokenRisks.ts @@ -0,0 +1,60 @@ +import type { TokenRisk, TokenRiskCounts } from '$lib/gen' + +/** Mirrors the 90 days the `token_risk` view (backend migrations) flags as unused. */ +export const STALE_TOKEN_DAYS = 90 + +/** How each risk the server flags reads, keyed in the order summaries and filters list them. */ +export const TOKEN_RISK_INFO: Record< + TokenRisk, + { + badge: string + color: 'red' | 'orange' | 'yellow' + tooltip: string + summary: (n: number) => string + } +> = { + superadmin: { + badge: 'Superadmin', + color: 'red', + tooltip: + 'Minted with superadmin rights and not narrowed by scopes: it carries full control of the instance', + summary: (n) => + n === 1 ? '1 token carries superadmin rights' : `${n} tokens carry superadmin rights` + }, + admin: { + badge: 'Admin', + color: 'orange', + tooltip: + 'Minted with admin rights and not narrowed by scopes: it carries full control of the workspace', + summary: (n) => (n === 1 ? '1 token carries admin rights' : `${n} tokens carry admin rights`) + }, + all_workspaces: { + badge: 'All workspaces', + color: 'orange', + tooltip: 'Not bound to a workspace: it reaches every workspace its owner belongs to', + summary: (n) => + n === 1 ? '1 token works in every workspace' : `${n} tokens work in every workspace` + }, + never_expires: { + badge: 'No expiration', + color: 'orange', + tooltip: 'Stays valid until it is deleted', + summary: (n) => (n === 1 ? '1 token never expires' : `${n} tokens never expire`) + }, + unused: { + badge: `Unused ${STALE_TOKEN_DAYS}d+`, + color: 'yellow', + tooltip: `Not used in over ${STALE_TOKEN_DAYS} days`, + summary: (n) => + n === 1 + ? `1 token has not been used in over ${STALE_TOKEN_DAYS} days` + : `${n} tokens have not been used in over ${STALE_TOKEN_DAYS} days` + } +} + +export const TOKEN_RISKS = Object.keys(TOKEN_RISK_INFO) as TokenRisk[] + +export function tokenRiskSummary(counts: TokenRiskCounts | undefined): string[] { + if (!counts) return [] + return TOKEN_RISKS.filter((r) => counts[r] > 0).map((r) => TOKEN_RISK_INFO[r].summary(counts[r])) +} diff --git a/frontend/src/lib/components/sidebar/Linkify.svelte b/frontend/src/lib/components/sidebar/Linkify.svelte index 0be0106e4b..a434d972d1 100644 --- a/frontend/src/lib/components/sidebar/Linkify.svelte +++ b/frontend/src/lib/components/sidebar/Linkify.svelte @@ -1,16 +1,13 @@ <script lang="ts"> - let { text } = $props() - // Function to convert text with URLs to HTML - function linkifyText(text) { - // Regex to match URLs starting with http/https and ending with ) - const urlRegex = /\(((https?:\/\/[^\s)]+))\)/g + import { splitLinks } from './linkify' - // Replace matched patterns with anchor tags - return text.replace(urlRegex, '(<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>)') - } + let { text }: { text: string | undefined | null } = $props() - let processedText = $derived(linkifyText(text)) + let parts = $derived(splitLinks(text)) </script> -<!-- Use @html to render the HTML --> -{@html processedText} +{#each parts as part, i (i)}{#if part.kind === 'link'}<a + href={part.href} + target="_blank" + rel="noopener noreferrer">{part.href}</a + >{:else}{part.value}{/if}{/each} diff --git a/frontend/src/lib/components/sidebar/SettingsMenu.svelte b/frontend/src/lib/components/sidebar/SettingsMenu.svelte index eac48da07c..6b1767289a 100644 --- a/frontend/src/lib/components/sidebar/SettingsMenu.svelte +++ b/frontend/src/lib/components/sidebar/SettingsMenu.svelte @@ -36,7 +36,8 @@ import MenuLink from './MenuLink.svelte' import SideBarNotification from './SideBarNotification.svelte' import { markChangelogsOpened, readRecentChangelogs } from './changelogs' - import { USER_SETTINGS_HASH, SUPERADMIN_SETTINGS_HASH } from './settings' + import { SUPERADMIN_SETTINGS_HASH } from './settings' + import { ACCOUNT_SETTINGS_LINKS } from '../account/accountSettingsLinks' import { accountSetup } from './accountSetup.svelte' import { EXECUTIONS_HINT } from './executionsHint' import { TOUR_PARAM, TOUR_PARAM_VALUE } from '$lib/components/tutorials/operatorTour' @@ -229,11 +230,11 @@ } ] : []), - { - displayName: 'Account settings', - icon: Settings, - href: USER_SETTINGS_HASH - }, + ...ACCOUNT_SETTINGS_LINKS.map((link) => ({ + displayName: link.label, + icon: link.icon, + href: link.href + })), // A superadmin who is not a member has no `usr` row, so there is no access to list. ...($userStore && !$userStore.non_member ? [ diff --git a/frontend/src/lib/components/sidebar/UserMenu.svelte b/frontend/src/lib/components/sidebar/UserMenu.svelte index ef2e2bdf31..6c090d8e10 100644 --- a/frontend/src/lib/components/sidebar/UserMenu.svelte +++ b/frontend/src/lib/components/sidebar/UserMenu.svelte @@ -10,10 +10,10 @@ roleCapabilities } from '$lib/stores' import { isRestricted } from '$lib/roleCapabilities' - import { USER_SETTINGS_HASH } from './settings' + import { ACCOUNT_SETTINGS_LINKS } from '../account/accountSettingsLinks' import { isCloudHosted } from '$lib/cloud' import { twMerge } from 'tailwind-merge' - import { Crown, KeyRound, ServerCog, LogOut, Moon, Settings, Sun, User } from 'lucide-svelte' + import { Crown, KeyRound, ServerCog, LogOut, Moon, Sun, User } from 'lucide-svelte' import { accountSetup } from './accountSetup.svelte' import DarkModeObserver from '../DarkModeObserver.svelte' import MenuButton from './MenuButton.svelte' @@ -94,10 +94,12 @@ Finish account setup </MenuItem> {/if} - <MenuItem href={USER_SETTINGS_HASH} class={itemClass} {item}> - <Settings size={16} /> - Account settings - </MenuItem> + {#each ACCOUNT_SETTINGS_LINKS as link (link.panel)} + <MenuItem href={link.href} class={itemClass} {item}> + <link.icon size={16} /> + {link.label} + </MenuItem> + {/each} <MenuItem onClick={() => { diff --git a/frontend/src/lib/components/sidebar/linkify.test.ts b/frontend/src/lib/components/sidebar/linkify.test.ts new file mode 100644 index 0000000000..a11ed829f2 --- /dev/null +++ b/frontend/src/lib/components/sidebar/linkify.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest' +import { splitLinks } from './linkify' + +describe('splitLinks', () => { + it('links parenthesised http urls and keeps the rest as text', () => { + expect(splitLinks('see (https://example.com/a?b=1) now')).toEqual([ + { kind: 'text', value: 'see (' }, + { kind: 'link', href: 'https://example.com/a?b=1' }, + { kind: 'text', value: ') now' } + ]) + }) + + it('keeps markup in the message as plain text', () => { + const text = 'script not found at name u/a/<img src=x onerror=alert(1)>' + expect(splitLinks(text)).toEqual([{ kind: 'text', value: text }]) + }) + + it('does not link other schemes', () => { + expect(splitLinks('(javascript:alert(1))')).toEqual([ + { kind: 'text', value: '(javascript:alert(1))' } + ]) + }) + + it('handles empty input', () => { + expect(splitLinks(undefined)).toEqual([]) + expect(splitLinks('')).toEqual([]) + }) +}) diff --git a/frontend/src/lib/components/sidebar/linkify.ts b/frontend/src/lib/components/sidebar/linkify.ts new file mode 100644 index 0000000000..568e8033ba --- /dev/null +++ b/frontend/src/lib/components/sidebar/linkify.ts @@ -0,0 +1,29 @@ +export type LinkifyPart = { kind: 'text'; value: string } | { kind: 'link'; href: string } + +// Only URLs wrapped in parentheses are turned into links, matching how alert messages quote them. +const URL_IN_PARENS = /\((https?:\/\/[^\s)]+)\)/g + +export function splitLinks(text: string | undefined | null): LinkifyPart[] { + const source = text ?? '' + const parts: LinkifyPart[] = [] + let last = 0 + for (const match of source.matchAll(URL_IN_PARENS)) { + const href = match[1] + const start = match.index! + 1 + if (!isHttpUrl(href)) continue + if (start > last) parts.push({ kind: 'text', value: source.slice(last, start) }) + parts.push({ kind: 'link', href }) + last = start + href.length + } + if (last < source.length) parts.push({ kind: 'text', value: source.slice(last) }) + return parts +} + +function isHttpUrl(value: string): boolean { + try { + const url = new URL(value) + return url.protocol === 'http:' || url.protocol === 'https:' + } catch { + return false + } +} diff --git a/frontend/src/lib/components/sidebar/settings.ts b/frontend/src/lib/components/sidebar/settings.ts index d3f5f9f48a..625973223d 100644 --- a/frontend/src/lib/components/sidebar/settings.ts +++ b/frontend/src/lib/components/sidebar/settings.ts @@ -1,6 +1,30 @@ export const USER_SETTINGS_HASH = '#user-settings' as const export const SUPERADMIN_SETTINGS_HASH = '#superadmin-settings' as const +export type AccountSettingsPanel = 'profile' | 'tokens' | 'ai' | 'mcp' + +const ACCOUNT_SETTINGS_PANELS: AccountSettingsPanel[] = ['tokens', 'ai', 'mcp'] + +/** `#user-settings` opens the profile, `#user-settings-<panel>` one of the other drawers. */ +export function accountSettingsHref(panel: AccountSettingsPanel): string { + return panel === 'profile' ? USER_SETTINGS_HASH : `${USER_SETTINGS_HASH}-${panel}` +} + +/** + * The account settings drawer a hash asks for. `#user-settings` is linked from the docs and + * from older instances, so it and any unknown `#user-settings-*` suffix open the profile. + */ +export function parseAccountSettingsHash(hash: string): AccountSettingsPanel | undefined { + if (!hash.startsWith(USER_SETTINGS_HASH)) return undefined + const suffix = hash.slice(USER_SETTINGS_HASH.length) + if (suffix !== '' && !suffix.startsWith('-')) return undefined + if (suffix.startsWith('-')) { + const panel = ACCOUNT_SETTINGS_PANELS.find((p) => p === suffix.slice(1)) + if (panel) return panel + } + return 'profile' +} + /** * `#superadmin-settings`, optionally `#superadmin-settings?tab=<tab id>` to open on one tab. * Undefined when the hash is not the instance settings one at all. diff --git a/frontend/src/lib/components/triggers/email/DefaultEmailConfigSection.svelte b/frontend/src/lib/components/triggers/email/DefaultEmailConfigSection.svelte index 9e3c501ccd..4b1e2c28e2 100644 --- a/frontend/src/lib/components/triggers/email/DefaultEmailConfigSection.svelte +++ b/frontend/src/lib/components/triggers/email/DefaultEmailConfigSection.svelte @@ -10,7 +10,7 @@ import Alert from '$lib/components/common/alert/Alert.svelte' import { base32 } from 'rfc4648' import { emptyString } from '$lib/utils' - import UserSettings from '$lib/components/UserSettings.svelte' + import TokensDrawer from '$lib/components/account/TokensDrawer.svelte' import TextInput from '$lib/components/text_input/TextInput.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' @@ -37,7 +37,7 @@ isFlow?: boolean runnableVersion?: string | undefined path: string - userSettings: UserSettings + userSettings: TokensDrawer emailDomain?: string | null email?: string } diff --git a/frontend/src/lib/components/triggers/email/DefaultEmailPanel.svelte b/frontend/src/lib/components/triggers/email/DefaultEmailPanel.svelte index cc6ea7d301..c80507806c 100644 --- a/frontend/src/lib/components/triggers/email/DefaultEmailPanel.svelte +++ b/frontend/src/lib/components/triggers/email/DefaultEmailPanel.svelte @@ -1,6 +1,6 @@ <script lang="ts"> import { enterpriseLicense, userStore } from '$lib/stores' - import UserSettings from '../../UserSettings.svelte' + import TokensDrawer from '$lib/components/account/TokensDrawer.svelte' import { generateRandomString } from '$lib/utils' import HighlightTheme from '../../HighlightTheme.svelte' import Alert from '../../common/alert/Alert.svelte' @@ -14,7 +14,7 @@ const operatingWorkspace = useOperatingWorkspace() - let userSettings: UserSettings | undefined = $state(undefined) + let userSettings: TokensDrawer | undefined = $state(undefined) interface Props { token: string scopes?: string[] @@ -52,10 +52,10 @@ <HighlightTheme /> -<UserSettings +<TokensDrawer bind:this={userSettings} - on:tokenCreated={(e) => { - token = e.detail + onTokenCreated={(newToken) => { + token = newToken triggerTokens?.listTokens() }} newTokenWorkspace={$operatingWorkspace} diff --git a/frontend/src/lib/components/triggers/http/RouteEditorInner.svelte b/frontend/src/lib/components/triggers/http/RouteEditorInner.svelte index 10506263ab..83021c91de 100644 --- a/frontend/src/lib/components/triggers/http/RouteEditorInner.svelte +++ b/frontend/src/lib/components/triggers/http/RouteEditorInner.svelte @@ -67,7 +67,7 @@ import LocalDraftBanner from '$lib/components/LocalDraftBanner.svelte' import TriggerSuspendedJobsAlert from '../TriggerSuspendedJobsAlert.svelte' import TriggerSuspendedJobsModal from '../TriggerSuspendedJobsModal.svelte' - import UserSettings from '$lib/components/UserSettings.svelte' + import TokensDrawer from '$lib/components/account/TokensDrawer.svelte' import Tooltip from '$lib/components/Tooltip.svelte' import { useOperatingUser, @@ -183,7 +183,7 @@ let suspendedJobsModal = $state<TriggerSuspendedJobsModal | null>(null) let originalConfig = $state<NewHttpTrigger | undefined>(undefined) - let userSettings = $state<UserSettings | undefined>(undefined) + let userSettings = $state<TokensDrawer | undefined>(undefined) let hasChanged = $derived(!deepEqual(getRouteConfig(), originalConfig ?? {})) let scopes = $derived(['http_triggers:read:' + path]) @@ -555,7 +555,7 @@ {/if} {#if authentication_method === 'windmill'} - <UserSettings + <TokensDrawer bind:this={userSettings} newTokenWorkspace={wsId} newTokenLabel={`http-${actingUser?.username ?? 'superadmin'}-${generateRandomString(4)}`} diff --git a/frontend/src/lib/components/triggers/native/NativeConnectionPicker.svelte b/frontend/src/lib/components/triggers/native/NativeConnectionPicker.svelte index c1c8e7493b..afcd7af8d2 100644 --- a/frontend/src/lib/components/triggers/native/NativeConnectionPicker.svelte +++ b/frontend/src/lib/components/triggers/native/NativeConnectionPicker.svelte @@ -13,7 +13,7 @@ useOperatingUser, useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' - import { connectNativeAccount, getServiceConfig } from './utils' + import { getServiceConfig } from './utils' interface Props { service: NativeServiceName @@ -52,15 +52,22 @@ const confirmationModal = createAsyncConfirmationModal() let connections = $state<NativeTriggerConnection[] | undefined>(undefined) - let connecting = $state(false) + let requiredScopes = $state<string[]>([]) let connectDrawer: AppConnectDrawer | undefined = $state(undefined) + const resourceType = $derived(getServiceConfig(service)?.resourceType) async function load() { try { - connections = await WorkspaceIntegrationService.listNativeTriggerConnections({ - workspace: $operatingWorkspace!, - serviceName: service - }) + ;[connections, requiredScopes] = await Promise.all([ + WorkspaceIntegrationService.listNativeTriggerConnections({ + workspace: $operatingWorkspace!, + serviceName: service + }), + WorkspaceIntegrationService.getNativeTriggerRequiredScopes({ + workspace: $operatingWorkspace!, + serviceName: service + }) + ]) } catch (err: any) { connections = [] sendUserToast(`Failed to load ${displayName} connections: ${err.body ?? err.message}`, true) @@ -81,39 +88,40 @@ else value = path } - async function connect(path: string) { - connecting = true - try { - path = await connectNativeAccount($operatingWorkspace!, service, path) - await load() - sendUserToast(`${displayName} account connected`) - onConnectionsChange?.() - select(path) - } catch (err: any) { - sendUserToast(`Could not connect ${displayName}: ${err.body ?? err.message}`, true) - throw err - } finally { - connecting = false - } + function connect() { + connectDrawer?.open(resourceType, undefined, requiredScopes, true) } + async function onConnected(path: string) { + await load() + onConnectionsChange?.() + select(path) + } + + /** Reconnecting asks for what triggers need plus what the account holds, so nothing else + * using it loses access. */ async function reconnect(c: NativeTriggerConnection) { if (c.owner && c.owner !== operatingUser.current?.username) { const confirmed = await confirmationModal.ask({ title: `Reconnect ${c.path} with your account?`, confirmationText: 'Reconnect', - children: `${c.path} will act as the ${displayName} account you sign in with, instead of ${c.owner}'s. Every trigger using it will act as you.` + children: `${c.path} will act as the ${displayName} account you sign in with, instead of ${c.owner}'s. Every trigger and runnable using it will act as you.` }) if (!confirmed) return } - await connect(c.path).catch(() => {}) + connectDrawer?.open( + resourceType, + c.path, + [...new Set([...requiredScopes, ...(c.scopes ?? [])])], + true + ) } async function disconnect(path: string) { const confirmed = await confirmationModal.ask({ title: `Disconnect ${path}?`, confirmationText: 'Disconnect', - children: `This deletes every ${displayName} trigger that uses this account, including ones other members created. This action cannot be undone.` + children: `This deletes the resource and variable at ${path}, which scripts and flows may also use, and every ${displayName} trigger that uses this account, including ones other members created. This action cannot be undone.` }) if (!confirmed) return try { @@ -132,17 +140,14 @@ } // Members cannot write the workspace connection; the server refuses anyone else it does not own. - // A resource connected elsewhere is deleted from Resources, where its other uses are visible. function canDisconnect(c: NativeTriggerConnection): boolean { - if (!c.managed) return false if (operatingUser.current?.is_admin) return true return !c.workspace && !!c.owner && c.owner === operatingUser.current?.username } - // The server lets only the connection's owner or an admin replace it, and never replaces a - // resource connected from Resources. + // Writers of its variable may reconnect it; offered to its owner and admins, the ones who + // know which account it should act as. function canReconnect(c: NativeTriggerConnection): boolean { - if (!c.managed) return false return ( !!operatingUser.current?.is_admin || (!!c.owner && c.owner === operatingUser.current?.username) @@ -172,7 +177,7 @@ onClear={() => select(undefined)} {clearable} disabled={disabled || locked} - loading={connections === undefined || connecting} + loading={connections === undefined} placeholder={placeholder ?? `Connect a ${displayName} account to create this trigger`} noItemsMsg="No {displayName} account connected yet" > @@ -183,7 +188,6 @@ unifiedSize="xs" variant="subtle" startIcon={{ icon: RefreshCw }} - disabled={connecting} onclick={() => (close(), reconnect(connection))} > Reconnect @@ -209,8 +213,8 @@ wrapperClasses="flex-1" btnClasses="rounded-none" startIcon={{ icon: Plus }} - disabled={disabled || connecting} - onclick={() => (close(), connectDrawer?.open(getServiceConfig(service)?.resourceType))} + {disabled} + onclick={() => (close(), connect())} > Connect a {displayName} account </Button> @@ -228,7 +232,6 @@ unifiedSize="xs" variant="subtle" startIcon={{ icon: RefreshCw }} - disabled={connecting} onclick={() => reconnect(current)} > Reconnect @@ -240,15 +243,26 @@ {@const missing = selected} <Alert type="warning" title="This account is missing permissions" size="xs"> <div class="flex flex-col gap-2"> - {#if missing.managed} + {#if canReconnect(missing)} <span> Triggers need {missing.missing_scopes?.join(', ')}. Reconnecting asks for them and keeps what the account already has. </span> + <div> + <Button + unifiedSize="xs" + variant="default" + wrapperClasses="w-fit" + startIcon={{ icon: RefreshCw }} + onclick={() => reconnect(missing)} + > + Reconnect + </Button> + </div> {:else} <span> - Triggers need {missing.missing_scopes?.join(', ')}. This resource was connected from - Resources, so connect a new account that grants them. + Triggers need {missing.missing_scopes?.join(', ')}. Ask {missing.owner ?? 'its owner'} to + reconnect it, or connect your own account. </span> <div> <Button @@ -256,24 +270,10 @@ variant="default" wrapperClasses="w-fit" startIcon={{ icon: Plus }} - disabled={disabled || connecting} - onclick={() => connectDrawer?.open(getServiceConfig(service)?.resourceType)} + {disabled} + onclick={connect} > - Connect a new account - </Button> - </div> - {/if} - {#if canReconnect(missing)} - <div> - <Button - unifiedSize="xs" - variant="default" - wrapperClasses="w-fit" - startIcon={{ icon: RefreshCw }} - disabled={connecting} - onclick={() => reconnect(missing)} - > - Reconnect + Connect your account </Button> </div> {/if} @@ -288,13 +288,6 @@ {/if} </div> -<AppConnectDrawer - bind:this={connectDrawer} - native={{ - title: `Connect a ${displayName} account`, - defaultName: `native_${service}`, - connect - }} -/> +<AppConnectDrawer bind:this={connectDrawer} on:refresh={(e) => onConnected(e.detail)} /> <ConfirmationModal {...confirmationModal.props} /> diff --git a/frontend/src/lib/components/triggers/native/NativeOAuthCallback.svelte b/frontend/src/lib/components/triggers/native/NativeOAuthCallback.svelte index e3499deb70..c14055ab1f 100644 --- a/frontend/src/lib/components/triggers/native/NativeOAuthCallback.svelte +++ b/frontend/src/lib/components/triggers/native/NativeOAuthCallback.svelte @@ -4,56 +4,69 @@ import { WorkspaceIntegrationService } from '$lib/gen' import Alert from '$lib/components/common/alert/Alert.svelte' import { Loader2 } from 'lucide-svelte' - import { decodeNativeOAuthState, postNativeOAuthResult } from './utils' + import { decodeNativeOAuthState, NATIVE_TRIGGER_SERVICES } from './utils' - let outcome = $state<{ ok: true; path: string } | { ok: false; error: string } | undefined>() + /** Finishes a connect made with a workspace OAuth app: exchanges the code, then hands the + * token to the resource connect drawer that opened this window, which saves it. */ + let error = $state<string | undefined>() + let done = $state(false) - async function finish(): Promise<{ ok: true; path: string } | { ok: false; error: string }> { - const error = page.url.searchParams.get('error') + async function finish() { + const providerError = page.url.searchParams.get('error') const code = page.url.searchParams.get('code') const state = page.url.searchParams.get('state') - if (error || !code || !state) { - return { ok: false, error: error ?? 'The provider returned no authorization code' } + if (providerError || !code || !state) { + return { + type: 'error', + error: providerError ?? 'The provider returned no authorization code' + } + } + // The signed state carries the workspace and service it was issued for, so this page works + // whatever workspace is selected and wherever the provider sends the user back. + const decoded = decodeNativeOAuthState(state) + if (!decoded) { + return { type: 'error', error: 'The provider returned an unrecognized state' } } try { - // The signed state carries the workspace and service it was issued for, so this page works - // whatever workspace is selected and wherever the provider sends the user back. - const decoded = decodeNativeOAuthState(state) - if (!decoded) { - return { ok: false, error: 'The provider returned an unrecognized state' } - } - const { workspace, service } = decoded - const path = await WorkspaceIntegrationService.nativeTriggerServiceCallback({ - workspace, - serviceName: service, + const res = await WorkspaceIntegrationService.nativeTriggerServiceCallback({ + workspace: decoded.workspace, + serviceName: decoded.service, requestBody: { code, state } }) - return { ok: true, path } + return { + type: 'success', + res, + resource_type: NATIVE_TRIGGER_SERVICES[decoded.service].resourceType + } } catch (err: any) { - return { ok: false, error: err.body ?? err.message ?? String(err) } + return { type: 'error', error: err.body ?? err.message ?? String(err) } } } onMount(async () => { - outcome = await finish() - postNativeOAuthResult(outcome) + const message = await finish() + if (message.type === 'error') error = message.error + else done = true if (window.opener) { + window.opener.postMessage(message, window.location.origin) window.close() + } else { + localStorage.setItem('oauth-callback', JSON.stringify(message)) } }) </script> <div class="max-w-lg mx-auto mt-16 px-4"> - {#if outcome === undefined} + {#if error} + <Alert type="error" title="Could not connect the account">{error}</Alert> + {:else if done} + <Alert type="success" title="Account connected"> + Return to the window you connected from to save it. + </Alert> + {:else} <div class="flex items-center gap-2 text-sm text-secondary"> <Loader2 class="animate-spin" size={16} /> Finishing the connection... </div> - {:else if outcome.ok} - <Alert type="success" title="Account connected"> - Saved as {outcome.path}. You can close this window. - </Alert> - {:else} - <Alert type="error" title="Could not connect the account">{outcome.error}</Alert> {/if} </div> diff --git a/frontend/src/lib/components/triggers/native/utils.ts b/frontend/src/lib/components/triggers/native/utils.ts index b05b3c049c..6c185e4879 100644 --- a/frontend/src/lib/components/triggers/native/utils.ts +++ b/frontend/src/lib/components/triggers/native/utils.ts @@ -17,22 +17,8 @@ export function useNativeConnection(): () => string | undefined { return getContext<(() => string | undefined) | undefined>(CONNECTION_CONTEXT) ?? (() => undefined) } -const CONNECT_MESSAGE = 'native_trigger_oauth' - -/** Turns the resource connect drawer into the connect step of a native trigger account. */ -export type NativeConnect = { - title: string - defaultName: string - /** Rejects when the connection was not saved; the drawer then stays open on the path. */ - connect: (path: string) => Promise<void> -} - -export type NativeOAuthMessage = - | { type: typeof CONNECT_MESSAGE; ok: true; path: string } - | { type: typeof CONNECT_MESSAGE; ok: false; error: string } - -/** The workspace and service a native trigger connect state was signed for. A login state has no - * `:`, so this is undefined for one. */ +/** The workspace and service a connect made with a workspace OAuth app was signed for. A login + * state has no `:`, so this is undefined for one. */ export function decodeNativeOAuthState( state: string ): { workspace: string; service: NativeServiceName } | undefined { @@ -62,56 +48,11 @@ export function workspaceAppRedirectUri( return `${origin}/oauth/callback/${NATIVE_TRIGGER_SERVICES[service].resourceType}` } -/** Hands the outcome of a connect popup back to the page that opened it. */ -export function postNativeOAuthResult( - result: { ok: true; path: string } | { ok: false; error: string } -) { - const message = { type: CONNECT_MESSAGE, ...result } as NativeOAuthMessage - window.opener?.postMessage(message, window.location.origin) -} - -/** - * Connect an account in a popup and resolve with the path of the saved connection. The - * connection is saved at `resourcePath`, or at the caller's default path when omitted. - */ -export async function connectNativeAccount( - workspace: string, - service: NativeServiceName, - resourcePath?: string -): Promise<string> { - const authUrl = await WorkspaceIntegrationService.generateNativeTriggerServiceConnectUrl({ - workspace, - serviceName: service, - requestBody: { resource_path: resourcePath } - }) - const popup = window.open(authUrl, '_blank', 'popup,width=600,height=750') - if (!popup) { - throw new Error('The connection window was blocked. Allow popups for this site and retry.') - } - return new Promise((resolve, reject) => { - const onMessage = (event: MessageEvent<NativeOAuthMessage>) => { - if (event.origin !== window.location.origin || event.data?.type !== CONNECT_MESSAGE) return - cleanup() - if (event.data.ok) resolve(event.data.path) - else reject(new Error(event.data.error)) - } - // The callback page posts its result and then closes itself, so a closed window may still - // have a message in flight: give it a moment before treating the close as a cancel. - const closedPoll = setInterval(() => { - if (popup.closed) { - clearInterval(closedPoll) - setTimeout(() => { - cleanup() - reject(new Error('The connection window was closed before finishing')) - }, 1000) - } - }, 500) - function cleanup() { - window.removeEventListener('message', onMessage) - clearInterval(closedPoll) - } - window.addEventListener('message', onMessage) - }) +/** The service whose workspace OAuth app can connect resources of this type, if any. */ +export function serviceForResourceType(resourceType: string): NativeServiceName | undefined { + return (Object.keys(NATIVE_TRIGGER_SERVICES) as NativeServiceName[]).find( + (s) => NATIVE_TRIGGER_SERVICES[s].resourceType === resourceType + ) } export interface NativeTriggerConfig { diff --git a/frontend/src/lib/components/triggers/webhook/WebhooksConfigSection.svelte b/frontend/src/lib/components/triggers/webhook/WebhooksConfigSection.svelte index 9053e70be7..8dae79eac3 100644 --- a/frontend/src/lib/components/triggers/webhook/WebhooksConfigSection.svelte +++ b/frontend/src/lib/components/triggers/webhook/WebhooksConfigSection.svelte @@ -18,11 +18,12 @@ import { apiBaseUrl } from '$lib/apiBaseUrl.svelte' import TriggerTokens from '../TriggerTokens.svelte' import { userStore } from '$lib/stores' - import UserSettings from '../../UserSettings.svelte' + import TokensDrawer from '$lib/components/account/TokensDrawer.svelte' import { generateRandomString } from '$lib/utils' import TextInput from '$lib/components/text_input/TextInput.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' import CollapseLink from '$lib/components/CollapseLink.svelte' + import TokenInspector from '$lib/components/settings/TokenInspector.svelte' import CopyableCodeBlock from '$lib/components/details/CopyableCodeBlock.svelte' import { markdown } from 'svelte-highlight/languages' import { @@ -86,10 +87,22 @@ } }) + /** The route the token test checks: the by-path form of the one the examples call. A by-hash + * or by-version route is gated by the same runnable scope, which the check only resolves + * from a path. */ + const webhookRoutePath = $derived.by(() => { + const base = `/api/w/${wsId}/jobs` + if (agent) return `${base}/run/agent/${path}` + const endpoint = + requestType == 'async' ? 'run' : requestType == 'sync' ? 'run_wait_result' : 'run_and_stream' + return `${base}/${endpoint}/${isFlow ? 'f' : 'p'}/${path}` + }) + let tokenTestOpen = $state(false) + let surface = $state('http') as 'http' | 'sdk' let example = $state('rest') as 'rest' | 'curl' | 'fetch' let promptOpen = $state(false) - let userSettings: UserSettings | undefined = $state() + let userSettings: TokensDrawer | undefined = $state() let requestType = $state(DEFAULT_WEBHOOK_TYPE) as 'async' | 'sync' | 'sync_sse' let callMethod = $state('post') as 'get' | 'post' let runnableId = $state('path') as 'runnableVersion' | 'path' @@ -335,10 +348,10 @@ done` } </script> -<UserSettings +<TokensDrawer bind:this={userSettings} - on:tokenCreated={(e) => { - token = e.detail + onTokenCreated={(newToken) => { + token = newToken triggerTokens?.listTokens() }} newTokenWorkspace={wsId} @@ -363,6 +376,18 @@ done` </Tooltip> </Button> </div> + <div class="mt-2"> + <CollapseLink text="Test this token" bind:open={tokenTestOpen}> + {#key `${callMethod} ${webhookRoutePath}`} + <TokenInspector + {token} + workspace={wsId} + defaultPath={webhookRoutePath} + defaultMethod={callMethod.toUpperCase()} + /> + {/key} + </CollapseLink> + </div> </Label> {/if} diff --git a/frontend/src/lib/components/workspaceSettings/CreateWorkspace.svelte b/frontend/src/lib/components/workspaceSettings/CreateWorkspace.svelte index 13ce0662d1..9889015516 100644 --- a/frontend/src/lib/components/workspaceSettings/CreateWorkspace.svelte +++ b/frontend/src/lib/components/workspaceSettings/CreateWorkspace.svelte @@ -5,13 +5,14 @@ import { workspaceStore } from '$lib/stores' import { goto } from '$app/navigation' import { page } from '$app/state' + import { toSameOriginRelativePath } from '$lib/logoutRedirect' interface Props { isFork?: boolean } let { isFork = false }: Props = $props() - const rd = page.url.searchParams.get('rd') + const rd = toSameOriginRelativePath(page.url.searchParams.get('rd')) </script> <CenteredModal title="{isFork ? 'Forking' : 'New'} Workspace" centerVertically={false}> diff --git a/frontend/src/lib/components/workspaceSettings/RulesetEditor.svelte b/frontend/src/lib/components/workspaceSettings/RulesetEditor.svelte index 7e4d68c6a4..8a150cd3fd 100644 --- a/frontend/src/lib/components/workspaceSettings/RulesetEditor.svelte +++ b/frontend/src/lib/components/workspaceSettings/RulesetEditor.svelte @@ -1,11 +1,14 @@ <script lang="ts"> - import { Section, Button, DrawerContent } from '$lib/components/common' + import { Section, Button, DrawerContent, Alert } from '$lib/components/common' import Toggle from '$lib/components/Toggle.svelte' import Label from '$lib/components/Label.svelte' import ManageGroupsLink from '$lib/components/ManageGroupsLink.svelte' import MultiSelect from '$lib/components/select/MultiSelect.svelte' import TextInput from '$lib/components/text_input/TextInput.svelte' - import { workspaceStore } from '$lib/stores' + import { superadmin, workspaceStore } from '$lib/stores' + import { isCloudHosted } from '$lib/cloud' + import { goto } from '$app/navigation' + import { resource } from 'runed' import { GroupService, UserService, @@ -48,6 +51,7 @@ let restrictPublicRunSharing = $state(hasRule('RestrictPublicRunSharing')) let restrictGuestAppDeployment = $state(hasRule('RestrictGuestAppDeployment')) let requireIsolatedForks = $state(hasRule('RequireIsolatedForks')) + let requireSso = $state(hasRule('RequireSso')) let selectedGroups = $state<string[]>( untrack(() => rule)?.bypass_groups?.map((g) => g.replace('g/', '')) ?? [] ) @@ -68,6 +72,7 @@ let initialRestrictPublicRunSharing = $state(hasRule('RestrictPublicRunSharing')) let initialRestrictGuestAppDeployment = $state(hasRule('RestrictGuestAppDeployment')) let initialRequireIsolatedForks = $state(hasRule('RequireIsolatedForks')) + let initialRequireSso = $state(hasRule('RequireSso')) let initialSelectedGroups = $state<string[]>( untrack(() => rule)?.bypass_groups ? untrack(() => rule)!.bypass_groups.map((g) => g.replace('g/', '')) @@ -115,6 +120,23 @@ } }) + // The rule only refuses new password members; these already in the workspace stay held by it. + const passwordMembers = resource( + () => (requireSso ? $workspaceStore : undefined), + async (workspace) => + workspace ? await WorkspaceService.listPasswordLoginMembers({ workspace }) : [] + ) + const heldPasswordMembers = $derived( + (passwordMembers.current ?? []).filter( + (m) => + !selectedUsers.includes(m.username) && !m.groups.some((g) => selectedGroups.includes(g)) + ) + ) + const passwordLoginDisabled = resource( + () => requireSso && !isCloudHosted(), + async (shown) => (shown ? await UserService.isPasswordLoginDisabled() : undefined) + ) + // Computed properties const hasUnsavedChanges = $derived( isCreateMode @@ -126,6 +148,7 @@ restrictPublicRunSharing || restrictGuestAppDeployment || requireIsolatedForks || + requireSso || selectedGroups.length > 0 || selectedUsers.length > 0 || forkRoleMapping.length > 0 @@ -137,6 +160,7 @@ restrictPublicRunSharing !== initialRestrictPublicRunSharing || restrictGuestAppDeployment !== initialRestrictGuestAppDeployment || requireIsolatedForks !== initialRequireIsolatedForks || + requireSso !== initialRequireSso || JSON.stringify([...selectedGroups].sort()) !== JSON.stringify([...initialSelectedGroups].sort()) || JSON.stringify([...selectedUsers].sort()) !== @@ -193,7 +217,8 @@ ...(restrictGuestAppDeployment ? ['RestrictGuestAppDeployment' as ProtectionRuleKind] : []), - ...(requireIsolatedForks ? ['RequireIsolatedForks' as ProtectionRuleKind] : []) + ...(requireIsolatedForks ? ['RequireIsolatedForks' as ProtectionRuleKind] : []), + ...(requireSso ? ['RequireSso' as ProtectionRuleKind] : []) ], bypass_groups: selectedGroups, bypass_users: selectedUsers, @@ -234,7 +259,8 @@ ...(restrictGuestAppDeployment ? ['RestrictGuestAppDeployment' as ProtectionRuleKind] : []), - ...(requireIsolatedForks ? ['RequireIsolatedForks' as ProtectionRuleKind] : []) + ...(requireIsolatedForks ? ['RequireIsolatedForks' as ProtectionRuleKind] : []), + ...(requireSso ? ['RequireSso' as ProtectionRuleKind] : []) ], bypass_groups: selectedGroups, bypass_users: selectedUsers, @@ -253,6 +279,7 @@ initialRestrictPublicRunSharing = restrictPublicRunSharing initialRestrictGuestAppDeployment = restrictGuestAppDeployment initialRequireIsolatedForks = requireIsolatedForks + initialRequireSso = requireSso initialSelectedGroups = clone(selectedGroups) initialSelectedUsers = clone(selectedUsers) initialForkRoleMapping = clone(forkRoleMapping) @@ -383,6 +410,46 @@ 'Only workspace admins and bypassers can mint a public link to a run (readable without login). The read-only link for workspace members stays available to everyone.' )} </div> + <div class="flex flex-col gap-1"> + <Toggle bind:checked={requireSso} options={{ right: 'Require SSO' }} /> + {@render description( + 'Every member other than a service account or a bypasser must sign in with SSO: a user signing in with a password cannot be added, invited or auto-added, and no member can be switched to a password login. Admins are held too.' + )} + {#if requireSso} + <div class="flex flex-col gap-2 pl-11 pt-1"> + {#if heldPasswordMembers.length > 0} + <Alert + type="warning" + size="xs" + title={`${heldPasswordMembers.length} ${heldPasswordMembers.length === 1 ? 'member signs' : 'members sign'} in with a password`} + > + The rule does not remove existing members. Move them to SSO, remove them, or add + them as bypassers: {heldPasswordMembers + .map((m) => `${m.username} (${m.email})`) + .join(', ')}. + </Alert> + {/if} + {#if !isCloudHosted()} + <Alert + type="info" + size="xs" + title="Usually better set on the instance" + actions={$superadmin + ? [{ label: 'Open instance settings', onClick: () => goto('#superadmin-settings') }] + : undefined} + > + Disable password login in the instance settings to require SSO of every user in + every workspace: it also stops password sign-in itself, which this rule does not. + {#if passwordLoginDisabled.current === true} + Password login is already disabled on this instance. + {:else if passwordLoginDisabled.current === false} + Password login is currently enabled on this instance. + {/if} + </Alert> + {/if} + </div> + {/if} + </div> </Section> <Section diff --git a/frontend/src/lib/components/workspaceSettings/WorkspaceIntegrations.svelte b/frontend/src/lib/components/workspaceSettings/WorkspaceIntegrations.svelte index 6076dd64f7..4d75cd696d 100644 --- a/frontend/src/lib/components/workspaceSettings/WorkspaceIntegrations.svelte +++ b/frontend/src/lib/components/workspaceSettings/WorkspaceIntegrations.svelte @@ -142,7 +142,7 @@ const confirmed = await confirmationModal.ask({ title: `Remove the ${displayName} configuration?`, confirmationText: 'Remove', - children: `This deletes the workspace's ${displayName} OAuth app, every ${displayName} account connected through it and all ${displayName} triggers, which stop receiving events. This action cannot be undone.` + children: `This deletes the workspace's ${displayName} OAuth app and all ${displayName} triggers, which stop receiving events. Resources connected through the app stay, but their tokens stop refreshing until they are reconnected. This action cannot be undone.` }) if (!confirmed) return diff --git a/frontend/src/lib/infer.ts b/frontend/src/lib/infer.ts index c39c95be79..c1b464a471 100644 --- a/frontend/src/lib/infer.ts +++ b/frontend/src/lib/infer.ts @@ -77,7 +77,7 @@ import wasmUrlAsset from 'windmill-parser-wasm-asset/windmill_parser_wasm_bg.was import initWacParser, { parse_workflow_as_code } from 'windmill-parser-wasm-wac' import wasmUrlWac from 'windmill-parser-wasm-wac/windmill_parser_wasm_bg.wasm?url' import { workspaceStore } from './stores.js' -import { argSigToJsonSchemaType } from 'windmill-utils-internal' +import { argSigToJsonSchemaType } from 'windmill-utils-internal/parse/parse-schema' import { type AssetWithAccessType } from './components/assets/lib.js' import { type ColumnLineage } from './components/assets/AssetGraph/parsePipelineAnnotations' diff --git a/frontend/src/lib/loginError.test.ts b/frontend/src/lib/loginError.test.ts index cf76dca5ec..56d053a1c7 100644 --- a/frontend/src/lib/loginError.test.ts +++ b/frontend/src/lib/loginError.test.ts @@ -1,5 +1,10 @@ import { describe, it, expect } from 'vitest' -import { loginErrorMessage } from './loginError' +import { + loginErrorDetail, + loginErrorMessage, + TOTP_INVALID_MESSAGE, + TOTP_REQUIRED +} from './loginError' describe('loginErrorMessage', () => { it('maps the backend rejection to one message for a wrong email and a wrong password', () => { @@ -21,6 +26,15 @@ describe('loginErrorMessage', () => { ) }) + it('recognises the two-factor responses of the login endpoint', () => { + expect(loginErrorDetail({ status: 400, body: 'Bad request: Two-factor code required' })).toBe( + TOTP_REQUIRED + ) + expect(loginErrorMessage({ status: 400, body: 'Bad request: Invalid two-factor code' })).toBe( + TOTP_INVALID_MESSAGE + ) + }) + it('never surfaces server text it does not recognise, to an unauthenticated visitor', () => { const sqlError = { status: 400, diff --git a/frontend/src/lib/loginError.ts b/frontend/src/lib/loginError.ts index d26f44abd6..4c6f2e4ecd 100644 --- a/frontend/src/lib/loginError.ts +++ b/frontend/src/lib/loginError.ts @@ -3,17 +3,32 @@ // error page — would otherwise be printed verbatim to an unauthenticated visitor. const KNOWN_LOGIN_ERRORS = ['Password login is disabled on this instance'] +/** The password matched and the account asks for its authenticator code: a prompt, not a failure. */ +export const TOTP_REQUIRED = 'Two-factor code required' + +/** The password matched, the instance requires a second factor and the account has none yet. */ +export const TOTP_SETUP_REQUIRED = 'Two-factor setup required' + +export const TOTP_INVALID_MESSAGE = 'Invalid authentication code.' + const GENERIC_LOGIN_ERROR = 'Could not sign you in. Please try again.' -export function loginErrorMessage(err: any): string { - // The API returns errors as plain text, prefixed by their class (e.g. "Bad request: Invalid - // login"); ApiError.message is only the HTTP status text. +// The API returns errors as plain text, prefixed by their class (e.g. "Bad request: Invalid +// login"); ApiError.message is only the HTTP status text. +export function loginErrorDetail(err: any): string { const raw = typeof err?.body === 'string' ? err.body : err?.body?.error?.message const body = typeof raw === 'string' ? raw : '' - const detail = body.replace(/^(Bad request|Internal|Error): /, '').trim() + return body.replace(/^(Bad request|Internal|Error): /, '').trim() +} + +export function loginErrorMessage(err: any): string { + const detail = loginErrorDetail(err) if (detail === 'Invalid login') { return 'Invalid email or password.' } + if (detail === 'Invalid two-factor code') { + return TOTP_INVALID_MESSAGE + } if (err?.status === 429) { return 'Too many login attempts. Please try again later.' } diff --git a/frontend/src/lib/logoutRedirect.test.ts b/frontend/src/lib/logoutRedirect.test.ts index a42a86e6ef..ee7ff664be 100644 --- a/frontend/src/lib/logoutRedirect.test.ts +++ b/frontend/src/lib/logoutRedirect.test.ts @@ -1,5 +1,40 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' -import { isValidLogoutRedirect, toSameOriginRelativePath } from './logoutRedirect' +import { + isBackendApiPath, + isValidLogoutRedirect, + parseHttpUrl, + toRedirectTarget, + toSameOriginRelativePath +} from './logoutRedirect' +import { hubBaseUrlStore } from './stores' +import { DEFAULT_HUB_BASE_URL } from './hub' + +describe('parseHttpUrl', () => { + it('accepts http and https URLs', () => { + expect(parseHttpUrl('https://example.com/cb')?.href).toBe('https://example.com/cb') + expect(parseHttpUrl('http://localhost:1234')?.port).toBe('1234') + }) + + it('rejects other schemes and malformed input', () => { + expect(parseHttpUrl('javascript:alert(1)//')).toBeUndefined() + expect(parseHttpUrl('javascript://%0aalert(1)//:80')).toBeUndefined() + expect(parseHttpUrl('data:text/html,x')).toBeUndefined() + expect(parseHttpUrl('/relative')).toBeUndefined() + expect(parseHttpUrl(null)).toBeUndefined() + }) + + it('rejects routes of the backend serving this page', () => { + vi.stubGlobal('window', { location: { origin: 'http://localhost:3000' } }) + try { + expect(parseHttpUrl('http://localhost:3000/api/w/ws/x')).toBeUndefined() + expect(parseHttpUrl('http://localhost:3000/%61pi/w/ws/x')).toBeUndefined() + expect(parseHttpUrl('http://localhost:3000/runs')?.pathname).toBe('/runs') + expect(parseHttpUrl('https://example.com/api/cb')?.pathname).toBe('/api/cb') + } finally { + vi.unstubAllGlobals() + } + }) +}) describe('isValidLogoutRedirect', () => { beforeEach(() => { @@ -23,6 +58,41 @@ describe('isValidLogoutRedirect', () => { expect(isValidLogoutRedirect('https://app.windmill.dev/foo')).toBe(true) }) + it('rejects non-web schemes whatever host they name', () => { + vi.stubGlobal('window', { location: { origin: 'https://app.windmill.dev' } }) + const targets = [ + 'javascript://windmill.dev/%0aalert(1)', + 'javascript://app.windmill.dev/%0aalert(1)', + 'javascript://hub.windmill.dev/%0aalert(1)', + 'JAVASCRIPT://windmill.dev/%0aalert(1)', + 'JavaScript://app.windmill.dev/%0aalert(1)', + ' javascript://windmill.dev/%0aalert(1)', + 'java\tscript://windmill.dev/%0aalert(1)', + 'data:text/html,<script>alert(1)</script>', + 'data://windmill.dev/x', + 'vbscript://windmill.dev/x', + 'blob:https://app.windmill.dev/x', + 'file://windmill.dev/etc/passwd' + ] + for (const t of targets) { + expect(isValidLogoutRedirect(t), t).toBe(false) + expect(toRedirectTarget(t), t).toBeNull() + } + expect(isValidLogoutRedirect('https://app.windmill.dev/runs')).toBe(true) + }) + + it('rejects non-web schemes naming a custom hub host', () => { + hubBaseUrlStore.set('https://hub.example.com') + try { + expect(isValidLogoutRedirect('https://hub.example.com/scripts')).toBe(true) + expect(isValidLogoutRedirect('javascript://hub.example.com/%0aalert(1)')).toBe(false) + expect(isValidLogoutRedirect('JAVASCRIPT://hub.example.com/%0aalert(1)')).toBe(false) + expect(isValidLogoutRedirect('data://hub.example.com/x')).toBe(false) + } finally { + hubBaseUrlStore.set(DEFAULT_HUB_BASE_URL) + } + }) + it('rejects cross-origin and protocol-relative', () => { expect(isValidLogoutRedirect('https://evil.com/')).toBe(false) expect(isValidLogoutRedirect('//evil.com')).toBe(false) @@ -41,6 +111,16 @@ describe('toSameOriginRelativePath', () => { vi.unstubAllGlobals() }) + it('keeps a same-origin URL with a doubled leading slash on this origin', () => { + expect(toSameOriginRelativePath('http://localhost:3000//evil.example/x')).toBe( + '/evil.example/x' + ) + expect(toSameOriginRelativePath('http://localhost:3000/a/..//evil.example')).toBe( + '/evil.example' + ) + expect(toRedirectTarget('http://localhost:3000//evil.example')).toBe('/evil.example') + }) + it('returns same-origin relative paths as-is', () => { expect(toSameOriginRelativePath('/a/nucleus/chat')).toBe('/a/nucleus/chat') expect(toSameOriginRelativePath('/runs?workspace=foo')).toBe('/runs?workspace=foo') @@ -96,3 +176,61 @@ describe('toSameOriginRelativePath', () => { expect(toSameOriginRelativePath('http://localhost:3000/')).toBe('/') }) }) + +describe('backend routes as redirect targets', () => { + beforeEach(() => { + vi.stubGlobal('window', { location: { origin: 'http://localhost:3000' } }) + }) + + afterEach(() => { + vi.unstubAllGlobals() + }) + + const backendPaths = [ + '/api/w/ws/jobs/run_wait_result/p/hub/1/x?a=1', + '/api', + '/api?x=1', + '/API/w/ws/x', + '/%61pi/w/ws/x', + '/%2561pi/w/ws/x', + '/./api/w/ws/x', + '/%2e/api/w/ws/x', + '/foo/../api/w/ws/x', + '/foo/%2e%2e/api/w/ws/x', + '/.//api/w/ws/x', + '/api%2fw/ws/x', + 'api/w/ws/x', + 'http://localhost:3000/api/w/ws/x', + 'http://localhost:3000/%61pi/w/ws/x' + ] + + it('isBackendApiPath matches api routes only', () => { + expect(isBackendApiPath('/api/w/x')).toBe(true) + expect(isBackendApiPath('/%61pi/x')).toBe(true) + expect(isBackendApiPath('/apis')).toBe(false) + expect(isBackendApiPath('/apps/get/u/admin/x')).toBe(false) + expect(isBackendApiPath('/x/api/y')).toBe(false) + expect(isBackendApiPath('/')).toBe(false) + }) + + it('toSameOriginRelativePath refuses them', () => { + for (const p of backendPaths) expect(toSameOriginRelativePath(p), p).toBeNull() + }) + + it('isValidLogoutRedirect refuses them, on any accepted host', () => { + for (const p of backendPaths) expect(isValidLogoutRedirect(p), p).toBe(false) + expect(isValidLogoutRedirect('https://app.windmill.dev/api/w/ws/x')).toBe(false) + expect(isValidLogoutRedirect('/\\evil.com')).toBe(false) + }) + + it('toRedirectTarget refuses them and keeps app targets', () => { + for (const p of backendPaths) expect(toRedirectTarget(p), p).toBeNull() + expect(toRedirectTarget('/runs?workspace=foo')).toBe('/runs?workspace=foo') + expect(toRedirectTarget('http://localhost:3000/apps/get/x')).toBe('/apps/get/x') + expect(toRedirectTarget('https://app.windmill.dev/foo')).toBe('https://app.windmill.dev/foo') + expect(toRedirectTarget('https://evil.com/foo')).toBeNull() + expect(toRedirectTarget('//evil.com')).toBeNull() + expect(toRedirectTarget('javascript:alert(1)')).toBeNull() + expect(toRedirectTarget(null)).toBeNull() + }) +}) diff --git a/frontend/src/lib/logoutRedirect.ts b/frontend/src/lib/logoutRedirect.ts index 8160dfd66d..d3e0f16004 100644 --- a/frontend/src/lib/logoutRedirect.ts +++ b/frontend/src/lib/logoutRedirect.ts @@ -1,12 +1,23 @@ import { get } from 'svelte/store' import { hubBaseUrlStore } from './stores' +import { hasControlChar, isBackendApiPath, toSameOriginRelativePath } from './navigationTarget' + +export { + isBackendApiPath, + isSameOriginBackendUrl, + parseHttpUrl, + toSameOriginRelativePath +} from './navigationTarget' export function isValidLogoutRedirect(url: string): boolean { if (url.startsWith('/') && !url.startsWith('//')) { - return true + return toSameOriginRelativePath(url) !== null } try { const parsed = new URL(url) + // Before any host check: `javascript://windmill.dev/%0a…` has hostname `windmill.dev`. + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false + if (isBackendApiPath(parsed.pathname)) return false // Same-origin absolute URLs are always safe: the user can only be sent // back to the site they're already on, which is never an open redirect. // Mirrors toSameOriginRelativePath()'s same-origin handling, and lets a @@ -30,41 +41,15 @@ export function isValidLogoutRedirect(url: string): boolean { } /** - * Reduces a redirect target to a safe same-origin relative path. - * - * Returns the path (`/foo?bar#baz`) when the input is either: - * - already an absolute-but-relative path (`/foo`) that isn't protocol-relative - * (`//evil.com`) or a back-slash trick (`/\\evil.com`), or - * - a full URL whose origin matches the current page's origin. - * - * Returns `null` for anything else (cross-origin URLs, protocol-relative paths, - * malformed input). Used to sanitize values flowing into `RelayState`, - * `localStorage.rd`, and post-login redirects so we don't either lose a valid - * same-origin deep link or open-redirect into a foreign origin. + * Reduces a post-login `rd` to a target the app may navigate to: a same-origin relative path + * (as {@link toSameOriginRelativePath}), or an absolute http(s) URL {@link isValidLogoutRedirect} + * accepts, kept as is for `window.location`. Anything else is `null`, never the raw value: + * a refused relative path handed on to `goto` would still be navigated to. */ -export function toSameOriginRelativePath(rd: string | null | undefined): string | null { - if (!rd) return null - if (rd.length > 2048) return null - if (hasControlChar(rd)) return null - if (rd.startsWith('/')) { - if (rd.startsWith('//') || rd.startsWith('/\\')) return null - return rd - } - if (typeof window === 'undefined') return null - try { - const url = new URL(rd, window.location.origin) - if (url.origin !== window.location.origin) return null - const path = url.pathname + url.search + url.hash - return path || '/' - } catch { +export function toRedirectTarget(rd: string | null | undefined): string | null { + const relative = toSameOriginRelativePath(rd) + if (relative) return relative + if (!rd || !(rd.startsWith('http://') || rd.startsWith('https://')) || hasControlChar(rd)) return null - } -} - -function hasControlChar(s: string): boolean { - for (let i = 0; i < s.length; i++) { - const c = s.charCodeAt(i) - if (c < 0x20 || c === 0x7f) return true - } - return false + return isValidLogoutRedirect(rd) ? rd : null } diff --git a/frontend/src/lib/mcpAuth.test.ts b/frontend/src/lib/mcpAuth.test.ts new file mode 100644 index 0000000000..05be32b3a0 --- /dev/null +++ b/frontend/src/lib/mcpAuth.test.ts @@ -0,0 +1,20 @@ +import { describe, it, expect, vi } from 'vitest' + +vi.mock('$lib/gen', () => ({ SettingService: {}, WorkspaceService: {} })) + +import { parseScopeParam } from './mcpAuth' + +describe('parseScopeParam', () => { + it('splits on spaces as the server does', () => { + expect(parseScopeParam(' mcp:scripts:f/x/* mcp:runnables_as_tools ')).toEqual([ + 'mcp:scripts:f/x/*', + 'mcp:runnables_as_tools' + ]) + }) + + it('refuses separators the server does not split on', () => { + for (const sep of ['\u0085', '\t', '\n', ' ', '
']) { + expect(parseScopeParam(`mcp:scripts:f/x/*${sep}mcp:all`)).toBeUndefined() + } + }) +}) diff --git a/frontend/src/lib/mcpAuth.ts b/frontend/src/lib/mcpAuth.ts index 69637337cc..02d7949087 100644 --- a/frontend/src/lib/mcpAuth.ts +++ b/frontend/src/lib/mcpAuth.ts @@ -1,5 +1,15 @@ import { SettingService, WorkspaceService } from '$lib/gen' +/** + * The scope tokens of an OAuth `scope` parameter, split on spaces as the server splits them, or + * undefined when it holds anything but printable ASCII: the server refuses those, and a separator + * only one side honours (U+0085, a tab) would let the page show other scopes than the grant's. + */ +export function parseScopeParam(scope: string): string[] | undefined { + if (!/^[\x20-\x7e]*$/.test(scope)) return undefined + return scope.split(' ').filter((s) => s.length > 0) +} + /** Every live workspace of the instance, for a superadmin granting an MCP token their rights. */ export async function listEveryWorkspace(): Promise<{ id: string; name: string }[]> { const all: { id: string; name: string; deleted?: boolean }[] = [] diff --git a/frontend/src/lib/navigationTarget.ts b/frontend/src/lib/navigationTarget.ts new file mode 100644 index 0000000000..ff24752561 --- /dev/null +++ b/frontend/src/lib/navigationTarget.ts @@ -0,0 +1,109 @@ +// Store-free on purpose: the opaque public-app viewer imports this, and its bundle must not +// statically pull in `$lib/stores` or the generated client (see publicAppApi.ts). + +/** + * Whether a URL path addresses the backend (`/api/...`) rather than a page of the app. + * + * A navigation the app starts itself reaches the backend as same-origin, which is what its + * cross-site GET checks trust, so a redirect target taken from a link must never be one. The + * path is decoded and re-normalized until stable, so `/%61pi`, `/./api`, `//api` and `/API` + * are caught whichever way the server ends up reading them. + */ +export function isBackendApiPath(pathname: string): boolean { + let p = pathname + for (let i = 0; i < 8; i++) { + let decoded: string + try { + decoded = decodeURIComponent(p) + } catch { + return true + } + const collapsed = decoded.replace(/[\\/]+/g, '/') + let next: string + try { + next = new URL(collapsed.startsWith('/') ? collapsed : '/' + collapsed, 'http://n').pathname + } catch { + return true + } + next = next.toLowerCase() + if (next === p) break + p = next + } + return p === '/api' || p.startsWith('/api/') +} + +/** Whether `url` is a backend route of the instance this page is served from. */ +export function isSameOriginBackendUrl(url: URL): boolean { + return ( + typeof window !== 'undefined' && + url.origin === window.location?.origin && + isBackendApiPath(url.pathname) + ) +} + +/** + * Reduces a redirect target to a safe same-origin relative path. + * + * Returns the path (`/foo?bar#baz`) when the input is either: + * - already an absolute-but-relative path (`/foo`) that isn't protocol-relative + * (`//evil.com`) or a back-slash trick (`/\\evil.com`), or + * - a full URL whose origin matches the current page's origin, + * and the path is not a backend route ({@link isBackendApiPath}). + * + * Returns `null` for anything else (cross-origin URLs, protocol-relative paths, + * malformed input). Used to sanitize values flowing into `RelayState`, + * `localStorage.rd`, and post-login redirects so we don't either lose a valid + * same-origin deep link or open-redirect into a foreign origin. + */ +export function toSameOriginRelativePath(rd: string | null | undefined): string | null { + if (!rd) return null + if (rd.length > 2048) return null + if (hasControlChar(rd)) return null + if (rd.startsWith('/')) { + if (rd.startsWith('//') || rd.startsWith('/\\')) return null + try { + if (isBackendApiPath(new URL(rd, 'http://n').pathname)) return null + } catch { + return null + } + return rd + } + if (typeof window === 'undefined') return null + try { + const url = new URL(rd, window.location.origin) + // A `blob:` URL takes the origin of the URL it wraps, which its pathname then holds. + if (url.protocol !== 'http:' && url.protocol !== 'https:') return null + if (url.origin !== window.location.origin) return null + if (isBackendApiPath(url.pathname)) return null + // `https://<this host>//evil.example` has the pathname `//evil.example`, which on its own + // is a protocol-relative URL to another host. + const pathname = url.pathname.replace(/^[/\\]+/, '/') + return pathname + url.search + url.hash + } catch { + return null + } +} + +/** + * Parses a navigation target taken from the page URL, accepting only `http:` and `https:`. + * A target from page input must go through this before it is assigned to `window.location`. + * A backend route of this instance is refused too (see {@link isBackendApiPath}). + */ +export function parseHttpUrl(raw: string | null | undefined): URL | undefined { + if (!raw) return undefined + try { + const url = new URL(raw) + if (url.protocol !== 'http:' && url.protocol !== 'https:') return undefined + return isSameOriginBackendUrl(url) ? undefined : url + } catch { + return undefined + } +} + +export function hasControlChar(s: string): boolean { + for (let i = 0; i < s.length; i++) { + const c = s.charCodeAt(i) + if (c < 0x20 || c === 0x7f) return true + } + return false +} diff --git a/frontend/src/lib/stores.ts b/frontend/src/lib/stores.ts index 16b62da863..4c623f7335 100644 --- a/frontend/src/lib/stores.ts +++ b/frontend/src/lib/stores.ts @@ -115,13 +115,23 @@ export const maybePremium: Readable<boolean> = derived( // polling or owning its own invalidation. export const workspaceMembershipVersion = writable<number>(0) export const usersWorkspaceStore = writable<UserWorkspaceList | undefined>(undefined) +/** + * A token the app mints for a workspace reaches it through a membership, or, for a superadmin + * who has none there, only by carrying superadmin rights (`super_admin: true`, which the server + * ignores for anyone else). + */ +export function needsSuperAdminFor(workspace: string): boolean { + return !(get(usersWorkspaceStore)?.workspaces ?? []).some((w) => w.id === workspace) +} // Stands in for `UserWorkspace.username` on entries with no `usr` row behind them. It // names nobody, so anything that would address a user by it (a `u/<username>/...` path) // must treat it as "no username here" rather than render it. export const NON_MEMBER_USERNAME = 'superadmin' export const superadmin = writable<string | false | undefined>(undefined) export const devopsRole = writable<string | false | undefined>(undefined) -export const lspTokenStore = writable<string | undefined>(undefined) +export const lspTokenStore = writable<{ workspace: string; token: string } | undefined>( + undefined +) export const hubBaseUrlStore = writable<string>(DEFAULT_HUB_BASE_URL) // Whether the store above is the instance's answer or still the default it was seeded with. // It reads as the public hub either way, which is fine for a link and wrong for anything @@ -218,6 +228,12 @@ export const CODE_COMPLETION_SETTING_NAME = 'codeCompletionSessionEnabled' export const COPILOT_SESSION_MODEL_SETTING_NAME = 'copilotSessionModel' export const COPILOT_SESSION_PROVIDER_SETTING_NAME = 'copilotSessionProvider' export const COPILOT_SESSION_REASONING_SETTING_NAME = 'copilotSessionReasoning' +export const SCRIPT_GEN_MODEL_SETTING_NAME = 'scriptGenModel' +export const SCRIPT_GEN_PROVIDER_SETTING_NAME = 'scriptGenProvider' +export const SCRIPT_GEN_REASONING_SETTING_NAME = 'scriptGenReasoning' +export const AI_REVIEW_MODEL_SETTING_NAME = 'aiReviewModel' +export const AI_REVIEW_PROVIDER_SETTING_NAME = 'aiReviewProvider' +export const AI_REVIEW_REASONING_SETTING_NAME = 'aiReviewReasoning' export const formatOnSave = writable<boolean>( getLocalSetting(FORMAT_ON_SAVE_SETTING_NAME) != 'false' ) diff --git a/frontend/src/lib/userDraft.svelte.ts b/frontend/src/lib/userDraft.svelte.ts index e28caeb895..0c5366120d 100644 --- a/frontend/src/lib/userDraft.svelte.ts +++ b/frontend/src/lib/userDraft.svelte.ts @@ -930,13 +930,25 @@ function releaseEntry(mk: string): void { */ function makeDetachedHandle<V>(defaultValue?: V): UserDraftHandle<V> { let val = $state<V | undefined>(snapshotDraftValue(defaultValue)) - return { - get draft(): V | undefined { - return val - }, - set draft(value: V | undefined) { - val = value - } + return new Handle<V>( + () => val, + (value) => (val = value) + ) +} + +// A class instance, not an object literal: `$state` proxies plain objects, so a literal +// stored in `useMany`'s `handles` would reach callers as a new proxy on every reconcile, +// and the reconcile's `===` no-op check would compare a proxy with its raw handle. +class Handle<V> implements UserDraftHandle<V> { + constructor( + private read: () => V | undefined, + private write: (value: V | undefined) => void + ) {} + get draft(): V | undefined { + return this.read() + } + set draft(value: V | undefined) { + this.write(value) } } @@ -950,15 +962,13 @@ function makeHandle<V>( // throwing — the consumer should already be torn down by then. const mk = mapKey(workspace, itemKind, path) const stateOf = (): DraftState<unknown> | undefined => entries.get(mk)?.state - return { - get draft(): V | undefined { - return stateOf()?.val as V | undefined - }, - set draft(value: V | undefined) { + return new Handle<V>( + () => stateOf()?.val as V | undefined, + (value) => { const state = stateOf() if (state) state.val = value } - } + ) } /** Test-only: clear all in-memory entries. */ diff --git a/frontend/src/lib/utils.ts b/frontend/src/lib/utils.ts index 91cd66eb86..2beaa4312a 100644 --- a/frontend/src/lib/utils.ts +++ b/frontend/src/lib/utils.ts @@ -828,8 +828,7 @@ export async function copyToClipboard(value?: string, sendToast = true): Promise textArea.select() try { - document.execCommand('copy') - success = true + success = document.execCommand('copy') } catch (error) { // ignore (success = false) } finally { @@ -1944,6 +1943,23 @@ export function parseS3Object(s3Object: S3Object): { s3: string; storage?: strin return { storage: match?.[1] || undefined, s3: match?.[2] ?? '' } } +const S3_IMAGE_EXTENSIONS = ['.png', '.jpeg', '.jpg', '.webp'] + +/** Whether a result's S3 object renders as an image. */ +export function isS3ImageKey(key: string): boolean { + return S3_IMAGE_EXTENSIONS.some((ext) => key.endsWith(ext)) +} + +/** The workspace's preview URL for an S3 image a job returned. */ +export function s3ImagePreviewUrl( + workspace: string, + s3object: { s3: string; storage?: string } +): string { + let url = `/api/w/${workspace}/job_helpers/load_image_preview?file_key=${encodeURIComponent(s3object.s3)}` + if (s3object.storage) url += `&storage=${s3object.storage}` + return url +} + export function formatS3Object(s3Object: S3Object): S3Uri { if (typeof s3Object === 'object') return `s3://${s3Object.storage ?? ''}/${s3Object.s3}` return s3Object diff --git a/frontend/src/lib/utils/approvalResultUrls.test.ts b/frontend/src/lib/utils/approvalResultUrls.test.ts new file mode 100644 index 0000000000..5d7c11c227 --- /dev/null +++ b/frontend/src/lib/utils/approvalResultUrls.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from 'vitest' +import { approvalPageHref, resumeRequestCredentials, signedResumeUrl } from './approvalResultUrls' + +const base = 'https://wm.example.com/run/abc?workspace=demo' +const job = '01a2230e-229e-7897-1356-31f6444b03e6' +const sig = 'ab'.repeat(32) +const resume = `https://wm.example.com/api/w/demo/jobs_u/resume/${job}/0/${sig}` +const cancel = `https://wm.example.com/api/w/demo/jobs_u/cancel/${job}/0/${sig}` +const otherResume = `https://wm-internal.example.net/api/w/demo/jobs_u/resume/${job}/0/${sig}` + +describe('signedResumeUrl', () => { + it('accepts the signed urls the instance generates, on any origin', () => { + expect(signedResumeUrl(resume, 'resume', base)).toBe(resume) + expect(signedResumeUrl(cancel, 'cancel', base)).toBe(cancel) + expect(signedResumeUrl(otherResume, 'resume', base)).toBe(otherResume) + expect(signedResumeUrl(`${resume}?approver=bob%40x.com`, 'resume', base)).toBe( + `${resume}?approver=bob%40x.com` + ) + expect(signedResumeUrl(`/api/w/demo/jobs_u/resume/${job}/3/${sig}`, 'resume', base)).toBe( + `https://wm.example.com/api/w/demo/jobs_u/resume/${job}/3/${sig}` + ) + }) + + it('refuses any other url', () => { + for (const value of [ + undefined, + '', + 42, + cancel, // wrong operation for the button + `/api/w/demo/jobs_u/flow/resume_suspended/${job}`, + '/api/w/demo/workspaces/archive', + `/api/w/demo/jobs_u/resume/${job}/0/${sig}/../../../../workspaces/archive`, + `/api/w/demo/jobs_u/resume/${job}/0/${sig}?x=1`, + `/api/w/demo/jobs_u/resume/${job}/0/${sig}#x`, + `/api/w/demo/jobs_u/resume/${job}/0/nothex`, + `/api/w/demo/jobs_u/resume/not-a-uuid/0/${sig}`, + `ftp://wm.example.com/api/w/demo/jobs_u/resume/${job}/0/${sig}`, + `javascript:fetch('/api/w/demo/jobs_u/resume/${job}/0/${sig}')` + ]) { + expect(signedResumeUrl(value, 'resume', base)).toBeUndefined() + } + }) +}) + +describe('resumeRequestCredentials', () => { + it('sends the session only to this instance', () => { + expect(resumeRequestCredentials(resume, base)).toBe('same-origin') + expect(resumeRequestCredentials(otherResume, base)).toBe('omit') + }) +}) + +describe('approvalPageHref', () => { + it('keeps a link to this instance or to the resume url instance', () => { + const page = `https://wm.example.com/approve/demo/${job}?token=t` + expect(approvalPageHref(page, base, undefined)).toBe(page) + expect(approvalPageHref(`/approve/demo/${job}`, base, undefined)).toBe( + `https://wm.example.com/approve/demo/${job}` + ) + const internal = `https://wm-internal.example.net/approve/demo/${job}?token=t` + expect(approvalPageHref(internal, base, otherResume)).toBe(internal) + }) + + it('drops a link elsewhere or with another scheme', () => { + expect(approvalPageHref('javascript:alert(1)', base, resume)).toBeUndefined() + expect(approvalPageHref('data:text/html,hi', base, resume)).toBeUndefined() + expect(approvalPageHref('https://other.example.com/approve', base, resume)).toBeUndefined() + expect(approvalPageHref('//other.example.com/approve', base, undefined)).toBeUndefined() + expect(approvalPageHref(undefined, base, resume)).toBeUndefined() + }) +}) diff --git a/frontend/src/lib/utils/approvalResultUrls.ts b/frontend/src/lib/utils/approvalResultUrls.ts new file mode 100644 index 0000000000..46c59b41ec --- /dev/null +++ b/frontend/src/lib/utils/approvalResultUrls.ts @@ -0,0 +1,62 @@ +import { safeHref } from './safeHref' + +const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}' +// The shape `build_resume_url` (backend jobs.rs) signs: workspace, job, resume id, hex HMAC. +const SIGNED_PATH = { + resume: new RegExp(`^/api/w/[\\w-]+/jobs_u/resume/${UUID}/\\d+/[0-9a-f]{64}$`, 'i'), + cancel: new RegExp(`^/api/w/[\\w-]+/jobs_u/cancel/${UUID}/\\d+/[0-9a-f]{64}$`, 'i') +} + +function httpUrl(value: unknown, base: string): URL | undefined { + if (typeof value !== 'string' || !value) return undefined + try { + const url = new URL(value, base) + return ['http:', 'https:'].includes(url.protocol) ? url : undefined + } catch { + return undefined + } +} + +/** + * The resume or cancel URL of an approval result, when it has the shape of a signed + * `jobs_u/resume|cancel` URL. A job result is written by whoever ran the job and the button + * sends the request from the viewer's browser, so any other URL is refused. The origin is free: + * the instance's BASE_URL need not be the address it is browsed at. + */ +export function signedResumeUrl( + value: unknown, + op: 'resume' | 'cancel', + base: string +): string | undefined { + const url = httpUrl(value, base) + if (!url || url.hash || !SIGNED_PATH[op].test(url.pathname)) return undefined + let otherParam = false + url.searchParams.forEach((_, k) => { + if (k !== 'approver') otherParam = true + }) + if (otherParam) return undefined + return url.href +} + +/** + * The signature alone authorizes a resume; the session only names the approver, so it goes + * only to this instance. + */ +export function resumeRequestCredentials(url: string, base: string): RequestCredentials { + return new URL(url, base).origin === new URL(base).origin ? 'same-origin' : 'omit' +} + +/** + * The approval page link of an approval result, kept only when it is an http(s) link to this + * instance or to the instance its signed resume URL points to. + */ +export function approvalPageHref( + value: unknown, + base: string, + resumeUrl: string | undefined +): string | undefined { + const url = httpUrl(value, base) + if (!url) return undefined + const allowed = [new URL(base).origin, ...(resumeUrl ? [new URL(resumeUrl).origin] : [])] + return allowed.includes(url.origin) ? safeHref(url.href, base) : undefined +} diff --git a/frontend/src/lib/utils/embedderMessage.test.ts b/frontend/src/lib/utils/embedderMessage.test.ts new file mode 100644 index 0000000000..e71c857d25 --- /dev/null +++ b/frontend/src/lib/utils/embedderMessage.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from 'vitest' +import { isFromEmbedder } from './embedderMessage' + +const self = {} as Window +const parent = {} as Window +const other = {} as Window +const ownOrigin = 'https://wm.example' + +describe('isFromEmbedder', () => { + it('accepts a same-origin embedder', () => { + expect( + isFromEmbedder( + { source: parent, origin: ownOrigin }, + { self, parent, ownOrigin, hasUrlToken: false } + ) + ).toBe(true) + }) + + it('accepts a cross-origin embedder only when the page carries a url token', () => { + const event = { source: parent, origin: 'vscode-webview://abc' } + expect(isFromEmbedder(event, { self, parent, ownOrigin, hasUrlToken: true })).toBe(true) + expect(isFromEmbedder(event, { self, parent, ownOrigin, hasUrlToken: false })).toBe(false) + }) + + it('ignores messages from windows other than the embedder', () => { + expect( + isFromEmbedder( + { source: other, origin: 'https://elsewhere.example' }, + { self, parent, ownOrigin, hasUrlToken: true } + ) + ).toBe(false) + }) + + it('ignores everything when the page is not embedded', () => { + expect( + isFromEmbedder( + { source: self, origin: ownOrigin }, + { self, parent: self, ownOrigin, hasUrlToken: true } + ) + ).toBe(false) + }) +}) diff --git a/frontend/src/lib/utils/embedderMessage.ts b/frontend/src/lib/utils/embedderMessage.ts new file mode 100644 index 0000000000..bd36fb6294 --- /dev/null +++ b/frontend/src/lib/utils/embedderMessage.ts @@ -0,0 +1,44 @@ +type EmbedderMessageContext = { + self: Window + parent: Window | null + ownOrigin: string + // The page was opened with a `wm_token`, so its API calls carry that token rather than the + // session cookie. + hasUrlToken: boolean +} + +// The dev pages are driven by whatever embeds them (the VS Code extension's webview). Only that +// embedder may drive them, and a cross-origin one only when it handed the page a token: without +// one, the page acts with the session cookie, which another site must never steer. +export function isFromEmbedder( + event: Pick<MessageEvent, 'source' | 'origin'>, + ctx: EmbedderMessageContext +): boolean { + if (!ctx.parent || ctx.parent === ctx.self) return false + if (event.source !== ctx.parent) return false + return event.origin === ctx.ownOrigin || ctx.hasUrlToken +} + +const warnedOrigins = new Set<string>() + +export function isFromWindowEmbedder(event: MessageEvent): boolean { + const ctx = { + self: window, + parent: window.parent, + ownOrigin: window.location.origin, + hasUrlToken: !!new URLSearchParams(window.location.search).get('wm_token') + } + const accepted = isFromEmbedder(event, ctx) + if ( + !accepted && + ctx.parent !== ctx.self && + event.source === ctx.parent && + !warnedOrigins.has(event.origin) + ) { + warnedOrigins.add(event.origin) + console.warn( + `Ignoring messages from ${event.origin}: the embedding page must be on ${ctx.ownOrigin}, or open this page with a wm_token.` + ) + } + return accepted +} diff --git a/frontend/src/lib/utils_workspace_deploy.ts b/frontend/src/lib/utils_workspace_deploy.ts index 48e3462799..f37f1c4b19 100644 --- a/frontend/src/lib/utils_workspace_deploy.ts +++ b/frontend/src/lib/utils_workspace_deploy.ts @@ -51,7 +51,7 @@ import { type DeployKind, type DeployResult, type TriggerDeployKind -} from 'windmill-utils-internal' +} from 'windmill-utils-internal/deploy' export type { DeployResult, DeployKind, TriggerDeployKind } diff --git a/frontend/src/routes/(root)/(logged)/+layout.svelte b/frontend/src/routes/(root)/(logged)/+layout.svelte index 6a49ab050a..842987c103 100644 --- a/frontend/src/routes/(root)/(logged)/+layout.svelte +++ b/frontend/src/routes/(root)/(logged)/+layout.svelte @@ -72,7 +72,7 @@ import { afterNavigate, beforeNavigate } from '$app/navigation' import { goto, isNewTabClick } from '$lib/navigation' import { registerToolDisplayActionHandler } from '$lib/components/copilot/chat/createdResourceActions.svelte' - import type UserSettings from '$lib/components/UserSettings.svelte' + import type AccountSettingsDrawers from '$lib/components/account/AccountSettingsDrawers.svelte' import type SuperadminSettings from '$lib/components/SuperadminSettings.svelte' import WindmillIcon from '$lib/components/icons/WindmillIcon.svelte' import { page } from '$app/state' @@ -81,7 +81,10 @@ getFavoriteHref, getFavoriteLabel } from '$lib/components/sidebar/FavoriteMenu.svelte' - import { parseSuperadminSettingsHash, USER_SETTINGS_HASH } from '$lib/components/sidebar/settings' + import { + parseAccountSettingsHash, + parseSuperadminSettingsHash + } from '$lib/components/sidebar/settings' import { isCloudHosted } from '$lib/cloud' import { PanelLeft, @@ -329,7 +332,7 @@ }) return unregisterNavigate }) - let userSettings: UserSettings | undefined = $state() + let userSettings: AccountSettingsDrawers | undefined = $state() let superadminSettings: SuperadminSettings | undefined = $state() let menuHidden = $state(false) let isDarkMode = useIsDarkMode() @@ -364,10 +367,7 @@ } function onQueryChangeUserSettings() { - if (userSettings && page.url.hash.startsWith(USER_SETTINGS_HASH)) { - const mcpMode = page.url.hash.includes('-mcp') - userSettings.openDrawer(mcpMode) - } + userSettings?.openFromHash(page.url.hash) } function onQueryChangeAdminSettings() { @@ -1025,7 +1025,7 @@ let userSettingsRequested = $state(false) let superadminSettingsRequested = $state(false) $effect(() => { - if (page.url.hash.startsWith(USER_SETTINGS_HASH)) userSettingsRequested = true + if (parseAccountSettingsHash(page.url.hash)) userSettingsRequested = true if (parseSuperadminSettingsHash(page.url.hash)) superadminSettingsRequested = true }) let dbManagerRequested = $state(false) @@ -1556,8 +1556,8 @@ outside this layout, and their shortcut must reopen the URL that is their creden wraps every workspace page, so a static import gates first paint, and a load on mount competes with the page for bandwidth (several of them reach monaco). --> {#if userSettingsRequested} - {#await import('$lib/components/UserSettings.svelte') then UserSettings} - <UserSettings.default bind:this={userSettings} showMcpMode={true} /> + {#await import('$lib/components/account/AccountSettingsDrawers.svelte') then AccountSettingsDrawers} + <AccountSettingsDrawers.default bind:this={userSettings} /> {/await} {/if} {#if accountSetup.pending} diff --git a/frontend/src/routes/(root)/(logged)/+page.svelte b/frontend/src/routes/(root)/(logged)/+page.svelte index 028e88c045..50e232b0cd 100644 --- a/frontend/src/routes/(root)/(logged)/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/+page.svelte @@ -17,6 +17,9 @@ import ItemsList from '$lib/components/home/ItemsList.svelte' import RecentRunsPanel from '$lib/components/home/RecentRunsPanel.svelte' import RecentRunsHeaderStatus from '$lib/components/home/RecentRunsHeaderStatus.svelte' + import WaitingApprovalsHeaderStatus from '$lib/components/home/WaitingApprovalsHeaderStatus.svelte' + import WaitingApprovalsPanel from '$lib/components/home/WaitingApprovalsPanel.svelte' + import { useWaitingApprovals } from '$lib/components/home/waitingApprovals.svelte' import { allRunsHref, itemHref, @@ -126,6 +129,17 @@ // The side panel needs the room of a desktop window; narrower, only the header status shows. const wide = new MediaQuery('min-width: 1024px') let showRunsPanel = $derived(showRuns && wide.current && runsPanelOpen.val) + // Read whether or not the workspace shows the user any item: someone who can only approve, + // through a group, may see none of its scripts or flows. + const waitingApprovals = useWaitingApprovals(() => $workspaceStore ?? undefined) + const approvalsSectionOpen = usePanelOpen('wm-home-approvals-open') + let showApprovalsPanel = $derived( + tab == 'workspace' && wide.current && approvalsSectionOpen.val && waitingApprovals.total > 0 + ) + let showApprovalsStatus = $derived(waitingApprovals.total > 0 && !showApprovalsPanel) + let showSideColumn = $derived(showRunsPanel || showApprovalsPanel) + const SIDE_CARD = + 'flex flex-col bg-surface-tertiary border border-border-light rounded-lg px-5 pt-2 pb-3 group-has-[[data-composer-open]]/home:bg-transparent group-has-[[data-composer-open]]/home:border-transparent' const runsMenuId = homeHeaderMenu.register(200, () => { const data = recentRuns.current if (!showRuns || showRunsPanel || !homeActionsGathered()) return [] @@ -348,6 +362,15 @@ {/snippet} {#snippet runsStatus()} + <!-- Stays in the bar when the other actions gather into ⋮, down to the hourglass and the count: + it is the one thing in the bar that waits on the user. --> + {#if showApprovalsStatus} + <WaitingApprovalsHeaderStatus + compact={homeActionsCompact()} + approvals={waitingApprovals} + onShowSection={wide.current ? () => (approvalsSectionOpen.val = true) : undefined} + /> + {/if} {#if showRuns && !showRunsPanel && !homeActionsGathered()} <RecentRunsHeaderStatus compact={homeActionsCompact()} @@ -373,17 +396,17 @@ <!-- Where edits to this workspace are made is a fact about the workspace, so it sits in the header with the workspace's own name rather than above the list. --> <PageHeaderContent actions={editRuleBadge} /> - <!-- After the home menu (order 100): the run status closes the bar. --> + <!-- After the home menu (order 100): the run statuses close the bar. --> <PageHeaderContent actions={runsStatus} actionsOrder={200} actionFolds={HOME_ACTION_FOLDS} - actionsVersion={homeActionsVersion()} + actionsVersion={`${homeActionsVersion()}:${showApprovalsStatus}`} /> <ForkWorkspaceBanner /> <WorkspaceDraftsBanner /> - <div class="flex w-full justify-center {showRunsPanel ? 'max-w-[1520px]' : ''}"> + <div class="flex w-full justify-center {showSideColumn ? 'max-w-[1520px]' : ''}"> <div class="flex flex-col items-center flex-1 min-w-0"> <!-- While the composer is open this column stays at the top and the lists scroll under it. Its parent holds the lists too, because a sticky element holds only inside its parent; its @@ -485,23 +508,41 @@ <ItemsList bind:this={itemsList} bind:subtab showEditButtons={showCreateButtons} /> {/if} </div> - {#if showRunsPanel} - <!-- Beside the composer and the items card, as one of the page's cards, and like them it - loses its frame while the composer is open. The page scrolls, so it holds to the top - and its list scrolls inside it. `data-works-with-composer`: a press in it leaves the - composer open, as one in the items card does. --> - <aside + {#if showSideColumn} + <!-- Beside the composer and the items card, as the page's cards, and like them its cards + lose their frame while the composer is open. The page scrolls, so the column holds to + the top and each list scrolls inside its card. `data-works-with-composer`: a press in + it leaves the composer open, as one in the items card does. --> + <div data-works-with-composer - class="sticky top-3 self-start shrink-0 w-[380px] max-[1180px]:w-[300px] -ml-2 mr-4 mt-3 mb-6 max-h-[calc(100dvh-48px-1.5rem)] flex flex-col bg-surface-tertiary border border-border-light rounded-lg px-5 pt-2 pb-3 group-has-[[data-composer-open]]/home:bg-transparent group-has-[[data-composer-open]]/home:border-transparent" - aria-label="Recently run" + class="sticky top-3 self-start shrink-0 w-[380px] max-[1180px]:w-[300px] -ml-2 mr-4 mt-3 mb-6 max-h-[calc(100dvh-48px-1.5rem)] flex flex-col gap-3" > - <RecentRunsPanel - runs={recentRuns} - folder={runsFolder} - onFocusItem={revealRunItem} - onCollapse={() => (runsPanelOpen.val = false)} - /> - </aside> + {#if showApprovalsPanel} + <!-- At most half the column with Recently run below it: a long queue scrolls inside. + The column has no height of its own, so a percentage would cap nothing. --> + <aside + class="{SIDE_CARD} min-h-0 {showRunsPanel + ? 'max-h-[calc((100dvh-48px-1.5rem)/2)]' + : ''}" + aria-label="Awaiting your approval" + > + <WaitingApprovalsPanel + approvals={waitingApprovals} + onCollapse={() => (approvalsSectionOpen.val = false)} + /> + </aside> + {/if} + {#if showRunsPanel} + <aside class="{SIDE_CARD} min-h-0 flex-1" aria-label="Recently run"> + <RecentRunsPanel + runs={recentRuns} + folder={runsFolder} + onFocusItem={revealRunItem} + onCollapse={() => (runsPanelOpen.val = false)} + /> + </aside> + {/if} + </div> {/if} </div> </div> diff --git a/frontend/src/routes/(root)/(logged)/oauth/mcp_authorize/+page@(root).svelte b/frontend/src/routes/(root)/(logged)/oauth/mcp_authorize/+page@(root).svelte index aa52c8cc75..ee8a73fa05 100644 --- a/frontend/src/routes/(root)/(logged)/oauth/mcp_authorize/+page@(root).svelte +++ b/frontend/src/routes/(root)/(logged)/oauth/mcp_authorize/+page@(root).svelte @@ -5,13 +5,18 @@ <script lang="ts"> import { page } from '$app/state' import CenteredModal from '$lib/components/CenteredModal.svelte' - import { Button } from '$lib/components/common' + import { Badge, Button } from '$lib/components/common' import MultiSelect from '$lib/components/select/MultiSelect.svelte' import Select from '$lib/components/select/Select.svelte' import Toggle from '$lib/components/Toggle.svelte' import McpAccessPicker, { type McpAccess } from '$lib/components/mcp/McpAccessPicker.svelte' - import { UserService, WorkspaceService } from '$lib/gen' - import { listEveryWorkspace } from '$lib/mcpAuth' + import { + McpOauthService, + UserService, + WorkspaceService, + type GetMcpOauthServerClientResponse + } from '$lib/gen' + import { listEveryWorkspace, parseScopeParam } from '$lib/mcpAuth' import { sendUserToast } from '$lib/toast' import { copyToClipboard } from '$lib/utils' import Copy from 'lucide-svelte/icons/copy' @@ -21,12 +26,23 @@ let isGateway = page.url.searchParams.get('gateway') === 'true' let workspaceId = $state(page.url.searchParams.get('workspace_id') || '') let clientId = page.url.searchParams.get('client_id') || '' - let clientName = page.url.searchParams.get('client_name') || 'Unknown Client' let redirectUri = page.url.searchParams.get('redirect_uri') || '' + // The name and redirect URIs come from the client's registration, not from the URL: anyone + // can link here, and the client picked its own name when it registered itself. + let client = $state<GetMcpOauthServerClientResponse>() + let clientLookupFailed = $state(false) + const clientName = $derived(client?.client_name ?? '') + const redirectRegistered = $derived(client?.redirect_uris.includes(redirectUri) ?? false) + McpOauthService.getMcpOauthServerClient({ clientId }) + .then((c) => (client = c)) + .catch((e) => { + // Logged out: the root layout is already sending the browser to the login page. + if (e?.status === 401) return + clientLookupFailed = true + }) // What the client asked for seeds the access picker; what is approved is the picker's. - const askedScopes = (page.url.searchParams.get('scope') || 'mcp:all') - .split(' ') - .filter((s) => s.startsWith('mcp:')) + const parsedScopes = parseScopeParam(page.url.searchParams.get('scope') || 'mcp:all') + const askedScopes = (parsedScopes ?? []).filter((s) => s.startsWith('mcp:')) // Both narrowings at once is a client requesting every scope it was offered, not a choice. const requestedScopes = askedScopes.includes('mcp:all') && @@ -45,9 +61,20 @@ // browser-executable schemes here too — this also neutralizes any client rows // registered before the backend fix. const DISALLOWED_REDIRECT_SCHEMES = ['javascript:', 'data:', 'vbscript:', 'blob:', 'file:'] + // The code lands on `redirectUri` as a top-level GET, so this instance's own API is no + // callback either. + function isOwnApiUrl(url: URL): boolean { + if (url.origin !== window.location.origin) return false + try { + return /^\/+api(\/|$)/i.test(decodeURIComponent(url.pathname)) + } catch { + return true + } + } function isSafeRedirectUri(uri: string): boolean { try { - return !DISALLOWED_REDIRECT_SCHEMES.includes(new URL(uri).protocol.toLowerCase()) + const url = new URL(uri) + return !DISALLOWED_REDIRECT_SCHEMES.includes(url.protocol.toLowerCase()) && !isOwnApiUrl(url) } catch { return false } @@ -72,7 +99,12 @@ } } const loopbackRedirect = redirectUriValid && isLoopbackUri(redirectUri) - const redirectOrigin = redirectUriValid ? new URL(redirectUri).origin : '' + // Where the code goes. A private-use scheme (vscode://, cursor://) has an opaque origin. + function redirectDestination(uri: string): string { + const url = new URL(uri) + return url.origin !== 'null' ? url.origin : `${url.protocol}//${url.host}` + } + const redirectOrigin = redirectUriValid ? redirectDestination(redirectUri) : '' let loading = $state(false) let success = $state(false) @@ -145,7 +177,7 @@ } function onDeny() { - if (!redirectUriValid) return + if (!redirectUriValid || !redirectRegistered) return // Redirect to client with error const params = new URLSearchParams({ error: 'access_denied', @@ -158,7 +190,7 @@ } async function onApprove() { - if (!redirectUriValid) return + if (!redirectUriValid || !redirectRegistered) return if (!grantsWorkspace) { sendUserToast('Please select a workspace', true) return @@ -221,7 +253,25 @@ {#if !redirectUriValid} <CenteredModal title="Authorization Request"> - <p class="text-center text-sm text-primary"> Error: invalid or unsafe redirect_uri </p> + <p class="text-center text-sm text-primary break-all"> + This client's redirect URI {redirectUri} cannot receive the authorization: it must be an + http(s) or app URL outside this instance's /api path. Register the client with its own + callback URL. + </p> + </CenteredModal> +{:else if clientLookupFailed || (client && !redirectRegistered)} + <CenteredModal title="Authorization Request"> + <p class="text-center text-sm text-primary"> + Error: unknown client, or a redirect_uri it did not register + </p> + </CenteredModal> +{:else if !client} + <CenteredModal title="Authorization Request"> + <p class="text-center text-sm text-secondary">Loading...</p> + </CenteredModal> +{:else if !parsedScopes} + <CenteredModal title="Authorization Request"> + <p class="text-center text-sm text-primary">Error: invalid scope</p> </CenteredModal> {:else if !isGateway && !workspaceId} <CenteredModal title="Authorization Request"> @@ -276,8 +326,9 @@ {/if} </div> {:else} - <p class="text-center text-sm text-primary mb-6"> + <p class="text-center text-sm text-primary mb-2"> <span class="font-semibold text-accent">{clientName}</span> + <Badge color="yellow" small>Unverified app</Badge> is requesting access to {#if isGateway} your Windmill workspaces. @@ -287,12 +338,15 @@ workspace. {/if} </p> - {#if loopbackRedirect} - <p class="text-center text-xs text-secondary -mt-4 mb-6"> - After you approve, {clientName} receives the sign-in at - <span class="font-mono">{redirectOrigin}</span>, an address on this computer. - </p> - {/if} + <p class="text-center text-xs text-secondary mb-2"> + After you approve, the sign-in is sent to + <span class="font-mono font-semibold text-emphasis break-all">{redirectOrigin}</span + >{#if loopbackRedirect}, an address on this computer{/if}. + </p> + <p class="text-center text-2xs text-tertiary mb-6"> + The app registered itself under this name, and Windmill has not checked who runs it. Approve + only if you started this sign-in and you recognize the address above. + </p> {#if isGateway} <div class="mb-6 flex flex-col gap-2"> diff --git a/frontend/src/routes/(root)/(logged)/svix/create-webhook/+page@(root).svelte b/frontend/src/routes/(root)/(logged)/svix/create-webhook/+page@(root).svelte index 7952e4b76d..4913923f88 100644 --- a/frontend/src/routes/(root)/(logged)/svix/create-webhook/+page@(root).svelte +++ b/frontend/src/routes/(root)/(logged)/svix/create-webhook/+page@(root).svelte @@ -2,24 +2,25 @@ import { run } from 'svelte/legacy' import ScriptPicker from '$lib/components/ScriptPicker.svelte' - import { Button } from '$lib/components/common' + import { Alert, Button } from '$lib/components/common' import { page } from '$app/stores' import { apiBaseUrl } from '$lib/apiBaseUrl.svelte' import InstanceUiSync from '$lib/components/InstanceUiSync.svelte' import { userStore, workspaceStore } from '$lib/stores' import { sendUserToast } from '$lib/toast' - import UserSettings from '$lib/components/UserSettings.svelte' + import TokensDrawer from '$lib/components/account/TokensDrawer.svelte' import { generateRandomString } from '$lib/utils' import Tooltip from '$lib/components/Tooltip.svelte' import WorkspaceMenu from '$lib/components/sidebar/WorkspaceMenu.svelte' import { Menubar } from '$lib/components/meltComponents' + import { parseHttpUrl } from '$lib/logoutRedirect' let itemPath: string | undefined = $state(undefined) let itemKind: 'script' | 'flow' | 'app' = $state('script') let clientName = $page.url.searchParams.get('domain') ?? undefined - let redirectURI = $page.url.searchParams.get('redirect_uri') + const redirectURL = parseHttpUrl($page.url.searchParams.get('redirect_uri')) - let userSettings: UserSettings | undefined = $state() + let userSettings: TokensDrawer | undefined = $state() let token: string | undefined = $state(undefined) let scopes: string[] = $state([]) @@ -45,15 +46,17 @@ } function redirectSuccess(webhook: string, token: string) { + if (!redirectURL) return const webhook_url = new URL(webhook) webhook_url.searchParams.append('token', token) - const url = new URL(redirectURI!) + const url = new URL(redirectURL) url.searchParams.append('webhook_url', webhook_url.toString()) window.location.href = url.toString() } function redirectCancel(e: string): void { - const url = new URL(redirectURI!) + if (!redirectURL) return + const url = new URL(redirectURL) url.searchParams.append('error', e) window.location.href = url.toString() } @@ -76,10 +79,10 @@ <!-- This page skips the logged layout, which is what normally loads the API base url. --> <InstanceUiSync /> -<UserSettings +<TokensDrawer bind:this={userSettings} - on:tokenCreated={(e) => { - token = e.detail + onTokenCreated={(newToken) => { + token = newToken }} newTokenLabel={`webhook-${$userStore?.username ?? 'superadmin'}-${generateRandomString(4)}`} {scopes} @@ -92,6 +95,15 @@ >{`${clientName} wants to create a webhook`}</h1 > </div> + {#if redirectURL} + <p class="text-center text-sm text-secondary"> + The webhook URL and its token will be sent to <b>{redirectURL.host}</b> + </p> + {:else} + <Alert type="error" title="Invalid redirect address"> + This link has no valid http or https redirect address, so the request cannot be completed. + </Alert> + {/if} <div class="flex flex-row gap-3 items-center"> <div class="flex items-center justify-center min-w-10 w-10 h-10 border-2 border-blue-500 text-blue-500 font-bold rounded-full" @@ -161,12 +173,16 @@ </div> <div class="flex flex-row gap-2 mt-10"> <Button - disabled={!itemPath || !token || token === ''} + disabled={!redirectURL || !itemPath || !token || token === ''} btnClasses="whitespace-normal break-words flex flex-wrap" on:click={() => itemPath && token && createWebhook(itemPath, itemKind, token)} >Approve and share with {clientName}</Button > - <Button color="red" on:click={() => redirectCancel('user_canceled')}>Cancel</Button> + <Button + color="red" + disabled={!redirectURL} + on:click={() => redirectCancel('user_canceled')}>Cancel</Button + > </div> </div> </div> diff --git a/frontend/src/routes/(root)/(logged)/user/(user)/accept_invite/+page.svelte b/frontend/src/routes/(root)/(logged)/user/(user)/accept_invite/+page.svelte index 6b731a4833..2f8687bca8 100644 --- a/frontend/src/routes/(root)/(logged)/user/(user)/accept_invite/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/user/(user)/accept_invite/+page.svelte @@ -1,5 +1,5 @@ <script lang="ts"> - import { run } from 'svelte/legacy'; + import { run } from 'svelte/legacy' import { goto } from '$lib/navigation' @@ -9,13 +9,13 @@ import { usersWorkspaceStore, workspaceStore } from '$lib/stores' import CenteredModal from '$lib/components/CenteredModal.svelte' import { Button } from '$lib/components/common' + import { toSameOriginRelativePath } from '$lib/logoutRedirect' let workspace_id = $page.url.searchParams.get('workspace') ?? '' let username = $state('') let errorUsername = $state('') let checking = $state(false) - async function acceptInvite(): Promise<void> { await UserService.acceptInvite({ requestBody: { @@ -25,7 +25,7 @@ }) usersWorkspaceStore.set(await WorkspaceService.listUserWorkspaces()) workspaceStore.set(workspace_id) - goto($page.url.searchParams.get('rd') ?? '/') + goto(toSameOriginRelativePath($page.url.searchParams.get('rd')) ?? '/') } async function validateName(username: string): Promise<void> { @@ -67,7 +67,7 @@ getAutomateUsernameCreationSetting() run(() => { validateName(username) - }); + }) </script> <!-- Enable submit form on enter --> diff --git a/frontend/src/routes/(root)/(logged)/user/(user)/instance_settings/+page.svelte b/frontend/src/routes/(root)/(logged)/user/(user)/instance_settings/+page.svelte index a5c1a3379e..2419853896 100644 --- a/frontend/src/routes/(root)/(logged)/user/(user)/instance_settings/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/user/(user)/instance_settings/+page.svelte @@ -22,6 +22,7 @@ import { onDestroy, tick } from 'svelte' import { SettingService, UserService } from '$lib/gen' import { sendUserToast } from '$lib/toast' + import { loginErrorDetail, TOTP_SETUP_REQUIRED } from '$lib/loginError' import TextInput from '$lib/components/text_input/TextInput.svelte' import Toggle from '$lib/components/Toggle.svelte' import SettingsPageHeader from '$lib/components/settings/SettingsPageHeader.svelte' @@ -94,6 +95,17 @@ let accountSubmitting = $state(false) let accountError = $state('') let showOssAccountDialog = $state(false) + // Offered only when this build serves two-factor authentication. When the instance + // requires it, the new account sets it up at the login page anyway. + let totpAvailable = $state(false) + let totpRequired = $state(false) + let setUpTotp = $state(true) + UserService.getTotpStatus() + .then((status) => { + totpAvailable = true + totpRequired = status.required + }) + .catch(() => {}) let ossAccountError = $state('') // --- Resource type sync (triggered on entering account step) --- @@ -294,13 +306,22 @@ } }) - const token = await UserService.login({ - requestBody: { email: newEmail, password: newPassword } - }) + let token: string | undefined + try { + token = await UserService.login({ + requestBody: { email: newEmail, password: newPassword } + }) + } catch (e) { + // The instance requires two-factor authentication: the password matched, and the new + // account sets it up at the login page. The current session removes the old account. + if (loginErrorDetail(e) !== TOTP_SETUP_REQUIRED) throw e + } - // Update the client token for subsequent requests - const { OpenAPI } = await import('$lib/gen') - OpenAPI.TOKEN = token + if (token) { + // Update the client token for subsequent requests + const { OpenAPI } = await import('$lib/gen') + OpenAPI.TOKEN = token + } try { await UserService.globalUserDelete({ email: oldEmail }) @@ -315,7 +336,8 @@ '/user/login?email=' + encodeURIComponent(newEmail) + '&password=' + - encodeURIComponent(newPassword) + encodeURIComponent(newPassword) + + (totpAvailable && !totpRequired && setUpTotp ? '&setup_2fa=1' : '') ) ) } catch (e: any) { @@ -367,6 +389,30 @@ size="md" /> </div> + {#if totpAvailable && totpRequired} + <Alert type="info" title="Two-factor authentication is required" size="xs"> + This instance requires it. After Set account & finish, you log in with this account + and set it up before getting in. + </Alert> + {:else if totpAvailable} + <Alert type="info" title="Recommended: two-factor authentication" size="xs"> + A superadmin account controls the whole instance. Protect it with a code from an + authenticator app on top of its password. + </Alert> + <div class="flex flex-col gap-1"> + <Toggle + bind:checked={setUpTotp} + options={{ right: 'Set up two-factor authentication next' }} + size="xs" + /> + {#if setUpTotp} + <p class="text-tertiary text-2xs"> + After Set account & finish, you log in with this account and set it up right + away. You can skip it. + </p> + {/if} + </div> + {/if} </div> </SettingCard> diff --git a/frontend/src/routes/(root)/(logged)/user/(user)/login/+page.svelte b/frontend/src/routes/(root)/(logged)/user/(user)/login/+page.svelte index 8500593592..4c5de1c317 100644 --- a/frontend/src/routes/(root)/(logged)/user/(user)/login/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/user/(user)/login/+page.svelte @@ -21,23 +21,24 @@ import LoginHeading from '$lib/components/LoginHeading.svelte' import { onMount } from 'svelte' import { refreshSuperadmin } from '$lib/refreshUser' - import { isValidLogoutRedirect, toSameOriginRelativePath } from '$lib/logoutRedirect' + import { isValidLogoutRedirect, toRedirectTarget } from '$lib/logoutRedirect' import { confirmPendingLoginMethod } from '$lib/lastLoginMethod' + import { parseAccountSettingsHash } from '$lib/components/sidebar/settings' const email = page.url.searchParams.get('email') ?? '' const password = page.url.searchParams.get('password') ?? '' const error = page.url.searchParams.get('error') ?? undefined + const offerTotpSetup = page.url.searchParams.get('setup_2fa') === '1' const rdFromStorage = localStorage.getItem('rd') || undefined if (rdFromStorage) { localStorage.removeItem('rd') } const rawRd = page.url.searchParams.get('rd') ?? rdFromStorage - // Reduce same-origin full URLs (e.g. the page URL persisted from + // Reduces same-origin full URLs (e.g. the page URL persisted from // PublicApp.svelte's /a/[...path]) to relative paths so the post-login - // redirect can honor them. Without this, rd falls into the - // `startsWith('http')` branch and gets bounced to '/' (or worse, hung). - const sameOriginRd = toSameOriginRelativePath(rawRd) - const rd = sameOriginRd ?? rawRd + // redirect can honor them, and drops anything that is not a valid target: + // a signed-in visitor is redirected without seeing the form. + const rd = toRedirectTarget(rawRd) ?? undefined let firstTime = $state(false) // A third-party login creates the account on first use, so the page only offers sign-up @@ -113,8 +114,8 @@ // See (root)/+layout.svelte for why /projects/import skips the picker. } else if (rd?.startsWith('/user/workspaces') || rd?.startsWith('/projects/import')) { goto(rd) - } else if (rd == '/#user-settings') { - goto(`/user/workspaces#user-settings`) + } else if (rd && rd.startsWith('/#') && parseAccountSettingsHash(rd.slice(1))) { + goto(`/user/workspaces${rd.slice(1)}`) } else { goto(`/user/workspaces${rd ? `?rd=${encodeURIComponent(rd)}` : ''}`) } @@ -171,6 +172,7 @@ {error} {password} {email} + {offerTotpSetup} autoRedirect={false} onOptionsLoaded={(options) => (hasThirdParty = options.hasThirdParty)} /> diff --git a/frontend/src/routes/(root)/(logged)/user/(user)/logout/+page@.svelte b/frontend/src/routes/(root)/(logged)/user/(user)/logout/+page@.svelte index c9623bc340..6cce9f4ae0 100644 --- a/frontend/src/routes/(root)/(logged)/user/(user)/logout/+page@.svelte +++ b/frontend/src/routes/(root)/(logged)/user/(user)/logout/+page@.svelte @@ -4,7 +4,7 @@ import { page } from '$app/state' import CenteredModal from '$lib/components/CenteredModal.svelte' import { clearUser } from '$lib/logout' - import { isValidLogoutRedirect } from '$lib/logoutRedirect' + import { toRedirectTarget } from '$lib/logoutRedirect' import { userStore } from '$lib/stores' import { onMount } from 'svelte' @@ -32,8 +32,9 @@ return } - if (rd && isValidLogoutRedirect(rd)) { - window.location.href = rd + const target = toRedirectTarget(rd) + if (target) { + window.location.href = target } else { window.location.href = '/user/login' } diff --git a/frontend/src/routes/(root)/(logged)/user/(user)/workspaces/+page.svelte b/frontend/src/routes/(root)/(logged)/user/(user)/workspaces/+page.svelte index 293fb75270..17c41b4ff8 100644 --- a/frontend/src/routes/(root)/(logged)/user/(user)/workspaces/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/user/(user)/workspaces/+page.svelte @@ -19,11 +19,10 @@ } from '$lib/stores' import { Button, Skeleton } from '$lib/components/common' import Toggle from '$lib/components/Toggle.svelte' - import UserSettings from '$lib/components/UserSettings.svelte' + import AccountSettingsDrawers from '$lib/components/account/AccountSettingsDrawers.svelte' import SuperadminSettings from '$lib/components/SuperadminSettings.svelte' import WindmillIcon from '$lib/components/icons/WindmillIcon.svelte' import CenteredModal from '$lib/components/CenteredModal.svelte' - import { USER_SETTINGS_HASH } from '$lib/components/sidebar/settings' import { switchWorkspace } from '$lib/storeUtils' import { GitFork, @@ -37,7 +36,7 @@ ServerCog } from 'lucide-svelte' import { isCloudHosted } from '$lib/cloud' - import { isValidLogoutRedirect, toSameOriginRelativePath } from '$lib/logoutRedirect' + import { toRedirectTarget } from '$lib/logoutRedirect' import { canCreateWorkspace } from '$lib/workspaceCreation' import SimpleCreateWorkspace from '$lib/components/workspaceSettings/SimpleCreateWorkspace.svelte' import AnimatedButton from '$lib/components/common/button/AnimatedButton.svelte' @@ -60,29 +59,18 @@ let workspaceHasForks = $state(false) let workspaceTreeView: WorkspaceTreeView | undefined = $state(undefined) - let userSettings: UserSettings | undefined = $state() + let userSettings: AccountSettingsDrawers | undefined = $state() let superadminSettings: SuperadminSettings | undefined = $state() // Sanitized here rather than at each hand-off below: all four send an absolute `rd` to // `window.location.href`, which unlike `goto` leaves the origin, and a fourth weaker copy // of the check is how one of them gets missed. Absolute targets keep the allowance the - // OAuth callback uses (`isValidLogoutRedirect`: same origin, `*.windmill.dev`, the hub), + // OAuth callback uses (`toRedirectTarget`: same origin, `*.windmill.dev`, the hub), // since honouring one is why those branches exist. Anything else falls back to '/'. - let rd = $derived.by(() => { - const raw = $page.url.searchParams.get('rd') - if (!raw) return null - // Truthy for a safe relative path and for a same-origin URL; null for `//host`, - // `/\host` and control characters, which read as relative but are not. - if (toSameOriginRelativePath(raw)) return raw - if (!raw.startsWith('http')) return null - return isValidLogoutRedirect(raw) ? raw : null - }) + let rd = $derived(toRedirectTarget($page.url.searchParams.get('rd'))) run(() => { - if (userSettings && $page.url.hash.startsWith(USER_SETTINGS_HASH)) { - const mcpMode = $page.url.hash.includes('-mcp') - userSettings.openDrawer(mcpMode) - } + userSettings?.openFromHash($page.url.hash) }) async function loadInvites() { @@ -426,9 +414,9 @@ <Button variant="accent" size="xs2" - href="/user/accept_invite?workspace={encodeURIComponent( - invite.workspace_id - )}{rd ? `&rd=${encodeURIComponent(rd)}` : ''}" + href="/user/accept_invite?workspace={encodeURIComponent(invite.workspace_id)}{rd + ? `&rd=${encodeURIComponent(rd)}` + : ''}" > Accept </Button> @@ -494,9 +482,9 @@ <Button variant="accent" unifiedSize="xs" - href="/user/accept_invite?workspace={encodeURIComponent( - invite.workspace_id - )}{rd ? `&rd=${encodeURIComponent(rd)}` : ''}" + href="/user/accept_invite?workspace={encodeURIComponent(invite.workspace_id)}{rd + ? `&rd=${encodeURIComponent(rd)}` + : ''}" > Accept </Button> @@ -550,7 +538,7 @@ dropdownItems={[ { label: 'User settings', - onClick: () => userSettings?.openDrawer(), + onClick: () => userSettings?.open('profile'), icon: User }, { label: 'Log out', onClick: () => logout(), icon: LogOut } @@ -562,7 +550,7 @@ <Button variant="default" unifiedSize="sm" - onClick={() => userSettings?.openDrawer()} + onClick={() => userSettings?.open('profile')} startIcon={{ icon: Settings }} dropdownItems={[{ label: 'Log out', onClick: () => logout(), icon: LogOut }]} > @@ -583,4 +571,4 @@ </p> </div> </div> --> -<UserSettings bind:this={userSettings} showMcpMode={true} /> +<AccountSettingsDrawers bind:this={userSettings} /> diff --git a/frontend/src/routes/(root)/(logged)/user/cli/+page.svelte b/frontend/src/routes/(root)/(logged)/user/cli/+page.svelte index d0b576c329..e1c836b28f 100644 --- a/frontend/src/routes/(root)/(logged)/user/cli/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/user/cli/+page.svelte @@ -1,17 +1,35 @@ <script lang="ts"> - import { onMount, untrack } from 'svelte' + import { onMount } from 'svelte' import { SettingService, UserService } from '$lib/gen' import { page } from '$app/state' import CenteredModal from '$lib/components/CenteredModal.svelte' - import { Button } from '$lib/components/common' + import { Alert, Button } from '$lib/components/common' import Select from '$lib/components/select/Select.svelte' - import { userStore, usersWorkspaceStore, workspaceStore } from '$lib/stores' + import Toggle from '$lib/components/Toggle.svelte' + import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte' + import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte' + import { superadmin, userStore, usersWorkspaceStore, workspaceStore } from '$lib/stores' import { parseMaxTokenExpirationDays } from '$lib/tokenExpiration' + import { parseHttpUrl } from '$lib/logoutRedirect' + import AdminRelianceNotice from '$lib/components/settings/AdminRelianceNotice.svelte' - let port = $state(Number(page.url.searchParams.get('port'))) - let host: string = page.url.searchParams.get('host') || 'localhost' - let scheme: string = page.url.searchParams.get('scheme') || 'http' - port = untrack(() => port) == 0 || Number.isNaN(untrack(() => port)) ? 80 : untrack(() => port) + const rawPort = Number(page.url.searchParams.get('port')) + const port = rawPort == 0 || Number.isNaN(rawPort) ? 80 : rawPort + const host = page.url.searchParams.get('host') || 'localhost' + const scheme = page.url.searchParams.get('scheme') || 'http' + // Exactly a scheme name: anything longer (`https://other.host/?`) would let the value + // itself pick the host the token is posted to, while the prompt shows `host`. + const callbackUrl = + scheme === 'http' || scheme === 'https' + ? parseHttpUrl(`${scheme}://${host}:${port}`) + : undefined + + // `host` may legitimately name a remote machine (a CLI run over SSH), so it is not refused, + // only flagged: the token then leaves the machine the user is sitting at. + function isLoopback(hostname: string): boolean { + const h = hostname.toLowerCase() + return h === 'localhost' || h === '[::1]' || /^127(\.\d{1,3}){3}$/.test(h) + } const DEFAULT_DAYS = 30 const CHOICES_DAYS = [1, 7, 30, 90, 365] @@ -54,7 +72,20 @@ return picked === 0 || picked > ceilingDays ? ceilingDays : picked }) + // Instance-wide by default: `wmill workspace add`, `workspace list/fork` and `instance` + // commands call instance-level endpoints, which a workspace-bound token is refused on. The + // owner's admin and superadmin rights are carried only when asked for. + // Binding is offered only for the workspace the CLI names (`&workspace=`): the CLI files the + // token under that profile, so a token bound to any other workspace would be refused there. + // An older CLI, or `wmill instance`, names none and gets an instance-wide token. + const cliWorkspace = page.url.searchParams.get('workspace') || undefined + let reach = $state<'workspace' | 'all'>('all') + let carryAdmin = $state(false) + let carrySuperAdmin = $state(false) + const isAdminSomewhere = $derived(!!$userStore?.is_admin || !!$superadmin) + async function authorizeToken(): Promise<void> { + if (!callbackUrl) return const username = $userStore?.username // `cli-login:` is reserved in `is_user_token` (windmill-common): the CLI signs in again on // its own once this token expires, so it must not email the user about it. @@ -66,20 +97,33 @@ const newToken = await UserService.createToken({ requestBody: { label, - expiration + expiration, + workspace_id: reach === 'workspace' ? cliWorkspace : undefined, + admin: carryAdmin, + super_admin: carrySuperAdmin } }) - const url = - scheme + '://' + host + ':' + port + '?token=' + newToken + '&workspace=' + $workspaceStore - window.location.href = url + const url = new URL(callbackUrl) + url.searchParams.set('token', newToken) + url.searchParams.set('workspace', cliWorkspace ?? $workspaceStore ?? '') + window.location.href = url.toString() } </script> <CenteredModal title="Authorize login request" inPage> - <p class="text-center text-lg mb-6"> - Token will be posted to {host == 'localhost' ? 'your local machine' : host} to port {port} - </p> + {#if callbackUrl} + <p class="text-center text-lg mb-6"> + Token will be posted to {callbackUrl.hostname == 'localhost' + ? 'your local machine' + : callbackUrl.hostname} to port {callbackUrl.port || + (callbackUrl.protocol === 'https:' ? 443 : 80)} + </p> + {:else} + <Alert type="error" title="Invalid login request" class="mb-6"> + This link does not name a valid http or https address to send the token to. + </Alert> + {/if} <div class="flex flex-col gap-1"> <span class="text-xs font-semibold text-emphasis">Token expires in</span> <Select @@ -94,8 +138,81 @@ Once it expires, the CLI asks you to sign in again. </p> </div> + {#if cliWorkspace} + <div class="flex flex-col gap-1 pt-4"> + <span class="text-xs font-semibold text-emphasis">Works in</span> + <ToggleButtonGroup bind:selected={reach} allowEmpty={false}> + {#snippet children({ item })} + <ToggleButton {item} value="all" label="All workspaces (instance-wide)" /> + <ToggleButton {item} value="workspace" label={`Only ${cliWorkspace}`} /> + {/snippet} + </ToggleButtonGroup> + <p class="text-2xs text-hint"> + {#if reach === 'all'} + Needed for <code>wmill workspace add</code>, <code>workspace list</code>/<code>fork</code> + and <code>instance</code> commands. + {:else} + Enough to sync {cliWorkspace}; commands that reach other workspaces or the instance are + refused. + {/if} + </p> + </div> + {/if} + {#if isAdminSomewhere} + <div class="flex flex-col gap-2 pt-4"> + {#if carrySuperAdmin} + <Toggle + checked + disabled + options={{ + right: 'Workspace admin rights', + rightTooltip: + 'Included in superadmin rights: the CLI is admin in every workspace it reaches.' + }} + size="xs" + /> + {:else} + <Toggle + bind:checked={carryAdmin} + options={{ + right: 'Workspace admin rights', + rightTooltip: + 'Needed to sync workspace settings, users and groups. Off, the CLI acts as a regular member of your workspaces.' + }} + size="xs" + /> + {/if} + {#if $superadmin} + <Toggle + bind:checked={carrySuperAdmin} + options={{ + right: 'Superadmin rights', + rightTooltip: + 'Needed for instance commands such as `wmill instance push`. Off, the CLI cannot reach instance settings or workspaces you are not a member of.' + }} + size="xs" + /> + {/if} + </div> + {/if} + {#if isAdminSomewhere && !carryAdmin && !carrySuperAdmin} + <div class="pt-4"> + <AdminRelianceNotice + workspaceIds={reach === 'workspace' && cliWorkspace ? [cliWorkspace] : undefined} + scopes={undefined} + /> + </div> + {/if} + {#if callbackUrl && !isLoopback(callbackUrl.hostname)} + <Alert type="warning" title="Token goes to another machine" class="mt-4"> + This will send a new token to <b>{callbackUrl.host}</b>, not to your machine. Only continue if + you started this login from a CLI running on that host. + </Alert> + {/if} <div class="flex flex-row justify-around pt-4 gap-x-1"> <Button variant="default" destructive unifiedSize="lg" href="/">Decline</Button> - <Button variant="accent" unifiedSize="lg" onClick={authorizeToken}>Authorize</Button> + <Button variant="accent" unifiedSize="lg" disabled={!callbackUrl} onClick={authorizeToken} + >Authorize</Button + > </div> </CenteredModal> diff --git a/frontend/src/routes/(root)/(logged)/user/remote_deploy_authorize/+page.svelte b/frontend/src/routes/(root)/(logged)/user/remote_deploy_authorize/+page.svelte index 90705bbdd1..b79b17abbb 100644 --- a/frontend/src/routes/(root)/(logged)/user/remote_deploy_authorize/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/user/remote_deploy_authorize/+page.svelte @@ -4,7 +4,7 @@ import { Alert, Button } from '$lib/components/common' import { UserService } from '$lib/gen' import { CALLBACK_PATH } from '$lib/remoteDeploy' - import { usersWorkspaceStore } from '$lib/stores' + import { needsSuperAdminFor, usersWorkspaceStore } from '$lib/stores' // Another Windmill instance asks for a token to deploy into one workspace here as the signed-in // user. It gets the token only if they authorize, and only at `callback`, whose origin they are @@ -58,7 +58,11 @@ // renewed by connecting again from the deploying instance, not managed here. label: `remote-deploy:${callback!.host}`, workspace_id: workspace, - expiration: new Date(Date.now() + TOKEN_LIFETIME_MS).toISOString() + expiration: new Date(Date.now() + TOKEN_LIFETIME_MS).toISOString(), + // Deploying as the user means with their admin rights there; superadmin rights + // only stand in for a membership the user does not have. + admin: true, + super_admin: needsSuperAdminFor(workspace) } }) sendBack({ token }) diff --git a/frontend/src/routes/(root)/(logged)/workers/+page.svelte b/frontend/src/routes/(root)/(logged)/workers/+page.svelte index 453a83daef..2ba4763ebd 100644 --- a/frontend/src/routes/(root)/(logged)/workers/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/workers/+page.svelte @@ -228,7 +228,8 @@ try { const licenseKey = (await SettingService.getGlobal({ - key: 'license_key' + key: 'license_key', + dangerouslyRevealSecrets: true })) as string if (!licenseKey) { diff --git a/frontend/src/routes/(root)/+layout.svelte b/frontend/src/routes/(root)/+layout.svelte index dddf1671ac..a8589578c2 100644 --- a/frontend/src/routes/(root)/+layout.svelte +++ b/frontend/src/routes/(root)/+layout.svelte @@ -14,6 +14,8 @@ } from '$lib/stores' import { getUserExt } from '$lib/user' import { sendUserToast } from '$lib/toast' + import { loginErrorDetail, TOTP_SETUP_REQUIRED } from '$lib/loginError' + import { USER_SETTINGS_HASH } from '$lib/components/sidebar/settings' import { switchWorkspace } from '$lib/storeUtils' import { forgetForkParent, getRememberedForkParent } from '$lib/forkParentMemory' import { onDestroy, onMount } from 'svelte' @@ -206,6 +208,26 @@ } } + // The instance now requires two-factor authentication and this account has none: the + // session is no longer renewed. Said once per page, with the way to keep it. + let totpSetupWarned = false + async function refreshSession(): Promise<void> { + try { + await UserService.refreshUserToken({ ifExpiringInLessThanS: 30 * 60 }) + } catch (e) { + if (loginErrorDetail(e) !== TOTP_SETUP_REQUIRED) throw e + if (totpSetupWarned) return + totpSetupWarned = true + sendUserToast( + 'This instance now requires two-factor authentication. Set it up to stay logged in: your session ends within 30 minutes otherwise.', + 'warning', + [{ label: 'Set up', callback: () => (location.hash = USER_SETTINGS_HASH) }], + undefined, + 30000 + ) + } + } + let interval: number | undefined = undefined onMount(() => { window.onunhandledrejection = (event: PromiseRejectionEvent) => { @@ -283,7 +305,7 @@ if (page.url.pathname != '/user/login') { setUserWorkspaceStore().catch((e) => console.error('could not load workspace list', e)) loadUser() - UserService.refreshUserToken({ ifExpiringInLessThanS: 30 * 60 }) + refreshSession() } let i = 0 @@ -295,7 +317,7 @@ if (i % 3 == 0) { console.debug('Refreshing user token') // every 15 minutes check if session token is expiring in less than 30min - await UserService.refreshUserToken({ ifExpiringInLessThanS: 30 * 60 }) + await refreshSession() } try { diff --git a/frontend/src/routes/(styled)/app_embed/[workspace]/[...path]/+page.svelte b/frontend/src/routes/(styled)/app_embed/[workspace]/[...path]/+page.svelte index e2866f5674..2f2f55d63d 100644 --- a/frontend/src/routes/(styled)/app_embed/[workspace]/[...path]/+page.svelte +++ b/frontend/src/routes/(styled)/app_embed/[workspace]/[...path]/+page.svelte @@ -9,6 +9,7 @@ * or the workspace chrome. `/apps/get` embeds this route in an opaque iframe. */ import { BROWSER } from 'esm-env' + import { encodePathParam } from '$lib/apiPathParams' import { AppService, OpenAPI } from '$lib/gen' import { userStore, workspaceStore } from '$lib/stores' import { setLicense } from '$lib/enterpriseUtils' @@ -35,9 +36,8 @@ headers['Authorization'] = `Bearer ${OpenAPI.TOKEN}` } const consent = opts?.sdkConsent ? '?sdk_consent=true' : '' - const res = await fetch(`${OpenAPI.BASE}/w/${workspace}/apps/embed_token/p/${path}${consent}`, { - headers - }) + const url = `${OpenAPI.BASE}/w/${encodePathParam('workspace', workspace)}/apps/embed_token/p/${encodePathParam('path', path)}${consent}` + const res = await fetch(url, { headers }) if (!res.ok) { const err: any = new Error('Failed to fetch embed token') err.status = res.status diff --git a/frontend/src/routes/(styled)/approve/[workspace]/[job]/+page.svelte b/frontend/src/routes/(styled)/approve/[workspace]/[job]/+page.svelte index c2f7945d15..2724007e45 100644 --- a/frontend/src/routes/(styled)/approve/[workspace]/[job]/+page.svelte +++ b/frontend/src/routes/(styled)/approve/[workspace]/[job]/+page.svelte @@ -6,13 +6,12 @@ import FlowMetadata from '$lib/components/FlowMetadata.svelte' import JobArgs from '$lib/components/JobArgs.svelte' import { onDestroy, onMount, untrack } from 'svelte' - import Tooltip from '$lib/components/Tooltip.svelte' import SchemaForm from '$lib/components/SchemaForm.svelte' import { enterpriseLicense, userStore, workspaceStore } from '$lib/stores' import Login from '$lib/components/Login.svelte' import { AlertTriangle, ExternalLink } from 'lucide-svelte' import { mergeSchema } from '$lib/common' - import { emptyString } from '$lib/utils' + import { displayDate, emptyString } from '$lib/utils' import { Alert } from '$lib/components/common' import DenyReason from '$lib/components/approvals/DenyReason.svelte' import { getUserExt } from '$lib/user' @@ -276,13 +275,19 @@ <h2 class="text-sm font-semibold text-emphasis">Approvers</h2> <div class="mt-2 text-xs font-normal text-primary"> {#if approvalInfo.approvers?.length > 0} + <!-- Worded as the run page's Approvals card words it. --> + {#if approvalInfo.required_events} + <p class="text-secondary mb-1"> + {approvalInfo.approvers.length} of {approvalInfo.required_events} approvals + </p> + {/if} <ul> {#each approvalInfo.approvers as a} <li> - <p> - {a.approver} - <Tooltip>Unique id of approval: {a.resume_id}</Tooltip> - </p> + {a.approver} + {#if a.approved_at} + <span class="text-hint">· {displayDate(a.approved_at)}</span> + {/if} </li> {/each} </ul> diff --git a/frontend/src/routes/(styled)/flows/dev/+page.svelte b/frontend/src/routes/(styled)/flows/dev/+page.svelte index e9a1c5773f..8d4829de67 100644 --- a/frontend/src/routes/(styled)/flows/dev/+page.svelte +++ b/frontend/src/routes/(styled)/flows/dev/+page.svelte @@ -20,6 +20,7 @@ import { deepEqual } from 'fast-equals' import { findModuleInFlow } from '$lib/components/flows/flowDiff' import { page } from '$app/state' + import { isFromWindowEmbedder } from '$lib/utils/embedderMessage' import { userStore, workspaceStore } from '$lib/stores' import { getUserExt } from '$lib/user' import DarkModeToggle from '$lib/components/sidebar/DarkModeToggle.svelte' @@ -140,7 +141,8 @@ connectWs() } - const el = (event) => { + const el = (event: MessageEvent) => { + if (!isFromWindowEmbedder(event)) return if (event.data.type == 'runTest') { runTest() } else if (event.data.type == 'replaceScript') { diff --git a/frontend/src/routes/(styled)/gh_success/+page.svelte b/frontend/src/routes/(styled)/gh_success/+page.svelte index 32fc31a6ea..99e450d26a 100644 --- a/frontend/src/routes/(styled)/gh_success/+page.svelte +++ b/frontend/src/routes/(styled)/gh_success/+page.svelte @@ -2,6 +2,7 @@ import { onMount } from 'svelte' import { CheckCircle, XCircle } from 'lucide-svelte' import { sendUserToast } from '$lib/toast' + import { encodePathParam } from '$lib/apiPathParams' let isLoading = $state(true) let isSuccess = $state(false) @@ -51,7 +52,8 @@ } try { - const response = await fetch(`/api/w/${workspace_id}/github_app/ghes_installation_callback`, { + const url = `/api/w/${encodePathParam('workspace', workspace_id)}/github_app/ghes_installation_callback` + const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' @@ -93,7 +95,8 @@ } try { - const response = await fetch(`/api/w/${workspace_id}/github_app/installation_callback`, { + const url = `/api/w/${encodePathParam('workspace', workspace_id)}/github_app/installation_callback` + const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' diff --git a/frontend/src/routes/(styled)/public_run/[workspace]/[id]/+page.svelte b/frontend/src/routes/(styled)/public_run/[workspace]/[id]/+page.svelte index 6f917aeeb6..496a680a45 100644 --- a/frontend/src/routes/(styled)/public_run/[workspace]/[id]/+page.svelte +++ b/frontend/src/routes/(styled)/public_run/[workspace]/[id]/+page.svelte @@ -7,10 +7,11 @@ import { setViewToken } from '$lib/viewToken' import { setLicense } from '$lib/enterpriseUtils' import { applyDarkModeVariant } from '$lib/darkModeVariant' - import { displayDate, isNotFlow, truncateRev } from '$lib/utils' + import { displayDate, isNotFlow, truncateRev, type StateStore } from '$lib/utils' import { Alert, Badge, Button, Skeleton } from '$lib/components/common' import DisplayResult from '$lib/components/DisplayResult.svelte' import FlowStatusViewer from '$lib/components/FlowStatusViewer.svelte' + import FlowProgressBar from '$lib/components/flows/FlowProgressBar.svelte' import JobArgs from '$lib/components/JobArgs.svelte' import JobLoader from '$lib/components/JobLoader.svelte' import JobStatus from '$lib/components/JobStatus.svelte' @@ -54,6 +55,9 @@ let loadError: { status?: number; message?: string } | undefined = $state(undefined) let jobLoader: JobLoader | undefined = $state(undefined) + // Runs nested under the flow that wait for events, filled by the graph as it loads them. + let suspendStatus: StateStore<Record<string, { job: Job; nb: number }>> = $state({ val: {} }) + let isFlow = $derived(job != undefined && !isNotFlow(job?.job_kind)) // Clear the previous run first: `isFlow` then falls back to false, which remounts the @@ -156,7 +160,16 @@ </div> {#if isFlow} + <!-- Drawn from the loaded job alone: it reads nothing the share token does not. --> + <FlowProgressBar + {job} + slim + textPosition="bottom" + showStepId + waitingNested={Object.keys(suspendStatus.val).length > 0} + /> <FlowStatusViewer + bind:suspendStatus jobId={job.id} initialJob={job} workspaceId={workspace} diff --git a/frontend/src/routes/(styled)/user/login_callback/[client_name]/+page.svelte b/frontend/src/routes/(styled)/user/login_callback/[client_name]/+page.svelte index 90c59ba68f..e667eb324b 100644 --- a/frontend/src/routes/(styled)/user/login_callback/[client_name]/+page.svelte +++ b/frontend/src/routes/(styled)/user/login_callback/[client_name]/+page.svelte @@ -9,7 +9,7 @@ import { userStore, usersWorkspaceStore, workspaceStore } from '$lib/stores' import { getUserExt } from '$lib/user' import { logoutWithRedirect } from '$lib/logoutKit' - import { isValidLogoutRedirect } from '$lib/logoutRedirect' + import { toRedirectTarget } from '$lib/logoutRedirect' import { parseQueryParams } from '$lib/utils' import { page } from '$app/state' import { isCloudHosted } from '$lib/cloud' @@ -32,7 +32,7 @@ if (rawRd) { localStorage.removeItem('rd') } - const rd = rawRd?.startsWith('http') && !isValidLogoutRedirect(rawRd) ? null : rawRd + const rd = toRedirectTarget(rawRd) const closeUponLogin = getCookie('close') == 'true' || localStorage.getItem('closeUponLogin') == 'true' // "Finish account setup" sent a signed-in account with no credentials of its own to a diff --git a/frontend/src/routes/a/[...path]/+page.svelte b/frontend/src/routes/a/[...path]/+page.svelte index 8bfd08a820..151498eb40 100644 --- a/frontend/src/routes/a/[...path]/+page.svelte +++ b/frontend/src/routes/a/[...path]/+page.svelte @@ -1,5 +1,6 @@ <script lang="ts"> import { BROWSER } from 'esm-env' + import { encodePathParam } from '$lib/apiPathParams' import { OpenAPI } from '$lib/gen/core/OpenAPI' import type { GuestEntry } from '$lib/gen/types.gen' @@ -97,7 +98,7 @@ for (let attempt = 0; attempt < 3; attempt++) { try { const entry = await publicGet<GuestEntry>( - `/apps_u/guest_entry_by_custom_path/${encodeURI(parsedCustomPath.path)}` + `/apps_u/guest_entry_by_custom_path/${encodePathParam('path', parsedCustomPath.path)}` ) guestAppPath = `${entry.workspace_id}/${entry.app_path}` guestEntry = 'guest' @@ -129,7 +130,7 @@ } const consent = opts?.sdkConsent ? '?sdk_consent=true' : '' const resp = await publicGet<{ token?: string; workspace_id?: string }>( - `/apps_u/embed_token_by_custom_path/${parsedCustomPath.path}${consent}` + `/apps_u/embed_token_by_custom_path/${encodePathParam('path', parsedCustomPath.path)}${consent}` ) embedWorkspace = resp.workspace_id ?? embedWorkspace return resp @@ -142,7 +143,7 @@ // rather than after it. The opaque viewer frame never fetches one. const userLoad = embedWorkspace ? getUserExtOrUndefined(embedWorkspace) : undefined const loaded = await publicGet<PublicAppValue>( - `/apps_u/public_app_by_custom_path/${encodeURI(parsedCustomPath.path)}` + `/apps_u/public_app_by_custom_path/${encodePathParam('path', parsedCustomPath.path)}` ) const appWorkspace = loaded.workspace_id! user = await (userLoad && embedWorkspace === appWorkspace diff --git a/frontend/src/routes/public/[workspace]/[...secret]/+page.svelte b/frontend/src/routes/public/[workspace]/[...secret]/+page.svelte index fb32a8ac9b..1f40b52a9a 100644 --- a/frontend/src/routes/public/[workspace]/[...secret]/+page.svelte +++ b/frontend/src/routes/public/[workspace]/[...secret]/+page.svelte @@ -1,5 +1,6 @@ <script lang="ts"> import { BROWSER } from 'esm-env' + import { encodePathParam } from '$lib/apiPathParams' import { OpenAPI } from '$lib/gen/core/OpenAPI' import type { GuestEntry } from '$lib/gen/types.gen' @@ -75,7 +76,9 @@ OpenAPI.TOKEN = 'jwt_ext_' + parsedSecret.jwt } const consent = opts?.sdkConsent ? '?sdk_consent=true' : '' - return await publicGet(`/w/${workspace}/apps_u/embed_token/${parsedSecret.secret}${consent}`) + return await publicGet( + `/w/${encodePathParam('workspace', workspace)}/apps_u/embed_token/${encodePathParam('path', parsedSecret.secret)}${consent}` + ) } // Viewer side: load the app + user using the embed token handed to the iframe. @@ -83,7 +86,7 @@ // Neither waits on the other: `app.html` already requested both. const userLoad = getUserExtOrUndefined(workspace) const appLoad = publicGet<PublicAppValue>( - `/w/${workspace}/apps_u/public_app/${encodeURI(parsedSecret.secret)}` + `/w/${encodePathParam('workspace', workspace)}/apps_u/public_app/${encodePathParam('path', parsedSecret.secret)}` ) appLoad.catch(() => {}) user = await userLoad @@ -117,7 +120,7 @@ for (let attempt = 0; attempt < 3; attempt++) { try { const entry = await publicGet<GuestEntry>( - `/w/${workspace}/apps_u/guest_entry/${encodeURI(parsedSecret.secret)}` + `/w/${encodePathParam('workspace', workspace)}/apps_u/guest_entry/${encodePathParam('path', parsedSecret.secret)}` ) guestAppPath = `${workspace}/${entry.app_path}` guestEntry = 'guest' diff --git a/frontend/svelte.config.js b/frontend/svelte.config.js index 64b39b5d7d..a2ddca5a42 100644 --- a/frontend/svelte.config.js +++ b/frontend/svelte.config.js @@ -40,7 +40,10 @@ const config = { $oauth_connect_registry: '../backend/oauth_connect.json', // The flow chat runs on the published SDK's source, so the product and the // package share one implementation (vite.config.js allows serving it). - 'windmill-chat': '../chat-sdk/src/index.ts' + 'windmill-chat': '../chat-sdk/src/index.ts', + // Source shared with the CLI. Import modules, not the index: the index reaches + // `src/gen`, which is generated and absent from a fresh checkout. + 'windmill-utils-internal': '../cli/windmill-utils-internal/src' } }, diff --git a/frontend/tailwind.config.cjs b/frontend/tailwind.config.cjs index 5c623fbadc..3feb32f1a4 100644 --- a/frontend/tailwind.config.cjs +++ b/frontend/tailwind.config.cjs @@ -552,7 +552,8 @@ const config = { 'spin-counter-clockwise': 'spin-counter-clockwise 1s linear infinite', 'zoom-in': 'zoom-in 0.25s ease-in-out', 'fade-out': 'fade-out 1s ease-in-out', - shake: 'shake 0.2s linear both' + shake: 'shake 0.2s linear both', + 'ring-fade': 'ring-fade 1.6s ease-in-out infinite' }, keyframes: { 'spin-counter-clockwise': { @@ -569,6 +570,10 @@ const config = { 'fade-out': { '0%': { opacity: '1' }, '100%': { opacity: '0' } + }, + 'ring-fade': { + '0%, 100%': { opacity: '1' }, + '50%': { opacity: '0.2' } } } } diff --git a/frontend/vite.config.js b/frontend/vite.config.js index 3f2befa0bc..987bfcb333 100644 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -253,7 +253,13 @@ function assertAiEngineFreeAppShell() { generateBundle(_options, bundle) { if (!isClientBuild(bundle)) return for (const entry of entries) { - assertStaticClosureExcludes(this, bundle, entry, forbidden, 'sessionRuntimeRegistry.svelte.ts') + assertStaticClosureExcludes( + this, + bundle, + entry, + forbidden, + 'sessionRuntimeRegistry.svelte.ts' + ) } } } @@ -434,11 +440,13 @@ const config = { ] }, cors: { origin: '*' }, - // `windmill-chat` (svelte.config.js alias) lives outside the frontend root. + // The `windmill-chat` and `windmill-utils-internal` aliases (svelte.config.js) live + // outside the frontend root. fs: { allow: [ searchForWorkspaceRoot(process.cwd()), - fileURLToPath(new URL('../chat-sdk', import.meta.url)) + fileURLToPath(new URL('../chat-sdk', import.meta.url)), + fileURLToPath(new URL('../cli/windmill-utils-internal', import.meta.url)) ] }, proxy: { @@ -558,6 +566,13 @@ const config = { test: /[\\/]src[\\/]lib[\\/]gen[\\/]core[\\/]OpenAPI\.ts$/, priority: 1 }, + // Imported by the generated client and by the public app routes alike, and + // importing nothing: left alone they land in a chunk those routes may not load. + { + name: 'url-helpers', + test: /[\\/]src[\\/]lib[\\/](apiPathParams|navigationTarget)\.ts$/, + priority: 1 + }, { name: 'gen', test: /[\\/]src[\\/]lib[\\/]gen[\\/]/ } ] } diff --git a/lsp/Pipfile b/lsp/Pipfile index 350454782d..cd9d2cb8f5 100644 --- a/lsp/Pipfile +++ b/lsp/Pipfile @@ -4,7 +4,7 @@ verify_ssl = true name = "pypi" [packages] -wmill = ">=1.884.1" +wmill = ">=1.894.1" sendgrid = "*" mysql-connector-python = "*" pymongo = "*" diff --git a/openflow.openapi.yaml b/openflow.openapi.yaml index fce7e70671..bd5a0a34b2 100644 --- a/openflow.openapi.yaml +++ b/openflow.openapi.yaml @@ -1,7 +1,7 @@ openapi: '3.0.3' info: - version: 1.884.1 + version: 1.894.1 title: OpenFlow Spec contact: name: Ruben Fiszel @@ -389,6 +389,12 @@ components: 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 + show_on_home: + type: boolean + description: >- + If true, a run waiting on this step is listed on the Home page of each user who + can approve it. Leave unset when the approval request is sent through another + channel (Slack, Discord, email), so it does not sit there unanswered priority: type: number description: Execution priority for this step (higher numbers run first) @@ -903,6 +909,9 @@ components: skip_failures: type: boolean description: If true, iteration failures don't stop the loop. Failed iterations return null + failure_threshold: + description: With skip_failures, the loop fails with an error named 'FailureThresholdReached' as soon as this many iterations have failed. Static number or expression (e.g. 'Math.ceil(flow_input.targets.length * 0.1)' for a percentage), evaluated once when the loop starts. A sequential loop stops at the iteration that reaches it. A parallel loop cancels the iterations no worker has picked up yet, including those held back by parallelism, while iterations already picked up finish; set parallelism to bound how many are in flight when the threshold is reached + $ref: '#/components/schemas/InputTransform' type: type: string enum: @@ -956,6 +965,9 @@ components: type: integer minimum: 1 description: Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted' + failure_threshold: + description: With skip_failures, the loop fails with an error named 'FailureThresholdReached' at the iteration that brings the failed iterations to this count. Static number or expression, evaluated once when the loop starts + $ref: '#/components/schemas/InputTransform' required: - modules - skip_failures @@ -1528,6 +1540,15 @@ components: type: integer approver: type: string + approved_at: + type: string + format: date-time + description: absent for approvals recorded before it was kept + approved: + type: boolean + description: > + false for a rejection the flow continued past; absent for approvals recorded + before it was kept required: - resume_id - approver diff --git a/powershell-client/WindmillClient/WindmillClient.psd1 b/powershell-client/WindmillClient/WindmillClient.psd1 index 928a5e90ba..300f32579d 100644 --- a/powershell-client/WindmillClient/WindmillClient.psd1 +++ b/powershell-client/WindmillClient/WindmillClient.psd1 @@ -12,7 +12,7 @@ RootModule = 'WindmillClient.psm1' # Version number of this module. - ModuleVersion = '1.884.1' + ModuleVersion = '1.894.1' # Supported PSEditions # CompatiblePSEditions = @() diff --git a/python-client/wmill/pyproject.toml b/python-client/wmill/pyproject.toml index 586ce6fa11..781e7ec1ed 100644 --- a/python-client/wmill/pyproject.toml +++ b/python-client/wmill/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "wmill" -version = "1.884.1" +version = "1.894.1" description = "A client library for accessing Windmill server wrapping the Windmill client API" license = "Apache-2.0" homepage = "https://windmill.dev" diff --git a/system_prompts/auto-generated/cli/cli-commands.md b/system_prompts/auto-generated/cli/cli-commands.md index de695045e7..5698dba453 100644 --- a/system_prompts/auto-generated/cli/cli-commands.md +++ b/system_prompts/auto-generated/cli/cli-commands.md @@ -32,12 +32,14 @@ app related commands - `--host <host:string>` - Host to bind the dev server to - `--entry <entry:string>` - Entry point file (default: index.ts for Svelte, index.tsx otherwise) - `--no-open` - Don't automatically open the browser + - `--run-install-scripts` - Run the dependencies' lifecycle scripts when installing node_modules - `--recording` - Frame the app in a shell with a Record button, to capture a replayable session recording of the app under development - `app lint [app_folder:string]` - Lint a raw app folder to validate structure and buildability - `--fix` - Attempt to fix common issues (not implemented yet) - `app bundle [app_folder:string]` - Bundle a raw app folder to js/css without deploying it - `--out <dir:string>` - Directory to write bundle.js and bundle.css into (default: <app_folder>/dist) - `--no-minify` - Skip minification + - `--run-install-scripts` - Run the dependencies' lifecycle scripts when installing node_modules - `app new` - create a new raw app from a template - `--summary <summary:string>` - App summary (short description). Skips the prompt when provided. Triggers non-interactive mode. - `--path <path:string>` - App path (e.g., f/folder/my_app or u/username/my_app). Skips the prompt when provided. Triggers non-interactive mode. @@ -125,6 +127,7 @@ Watch local file changes and live-reload the dev page for preview. Does NOT depl - `--proxy-port <port:number>` - Port for a localhost reverse proxy to the remote Windmill server - `--path <path:string>` - Watch a specific windmill path (e.g., u/admin/my_script or f/my_flow) - `--no-open` - Do not open the browser automatically +- `--host <host:string>` - Address to bind the dev server to: a loopback address or 0.0.0.0 for every interface (default: 127.0.0.1, this machine only) ### digest @@ -325,6 +328,7 @@ sync local with a remote instance or the opposite (push or pull) - `--dry-run` - Perform a dry run without making changes - `--skip-users` - Skip pulling users - `--skip-settings` - Skip pulling settings + - `--show-secrets` - Pull secrets (license key, passwords, tokens) in clear instead of redacted - `--skip-configs` - Skip pulling configs (worker groups) - `--skip-groups` - Skip pulling instance groups - `--include-workspaces` - Also pull workspaces @@ -347,7 +351,7 @@ sync local with a remote instance or the opposite (push or pull) - `instance whoami` - Display information about the currently logged-in user - `instance get-config` - Dump the current instance config (global settings + worker configs) as YAML - `-o, --output-file <file:string>` - Write YAML to a file instead of stdout - - `--show-secrets` - Include sensitive fields (license key, JWT secret) without prompting + - `--show-secrets` - Include secrets (license key, passwords, tokens) in clear without prompting - `--instance <instance:string>` - Name of the instance, override the active instance - `instance connect-slack` - Non-interactively connect Slack at the instance level using a pre-minted bot token (xoxb-...). Produces the same artifacts as the UI OAuth flow: global_settings 'slack' row + encrypted f/slack_bot/global_bot_token variable and resource in the admins workspace. - `--bot-token <bot_token:string>` - Slack bot token (xoxb-...) @@ -700,6 +704,13 @@ Manage API tokens - `token create` - Create a new API token - `--label <label:string>` - Token label - `--expiration <expiration:string>` - Token expiration (ISO 8601 timestamp) + - `--all-workspaces` - Do not bind the token to the current workspace: it then reaches every workspace you are a member of and instance-level endpoints + - `--admin` - Carry your workspace admin rights (off by default) + - `--superadmin` - Carry your superadmin rights (off by default) + - `--scope <scope:string>` - Restrict the token to this scope (e.g. jobs:run, scripts:read:f/folder/*). Repeatable. Omit for no scope restriction. +- `token update-scopes <token_prefix:string>` - Replace the scopes of one of your tokens, by its prefix + - `--scope <scope:string>` - Scope the token is restricted to (e.g. jobs:run, scripts:read:f/folder/*). Repeatable; replaces all existing scopes. + - `--clear` - Remove every scope restriction (the token keeps its workspace binding and admin/superadmin rights) - `token delete <token_prefix:string>` - Delete a token by its prefix ### trash @@ -759,6 +770,8 @@ user related commands - `user create-token` - Create a new API token for the authenticated user - `--email <email:string>` - Specify credentials to use for authentication. This will not be stored. It will only be used to exchange for a token with the API server, which will not be stored either. - `--password <password:string>` - Specify credentials to use for authentication. This will not be stored. It will only be used to exchange for a token with the API server, which will not be stored either. + - `--admin` - Carry your workspace admin rights (off by default) + - `--superadmin` - Carry your superadmin rights (off by default) ### variable diff --git a/system_prompts/auto-generated/flow.md b/system_prompts/auto-generated/flow.md index 9c7a67f8eb..e86a440cf6 100644 --- a/system_prompts/auto-generated/flow.md +++ b/system_prompts/auto-generated/flow.md @@ -315,6 +315,7 @@ can call one, not an agent used as a tool. ## Loop Structure Rules - 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 +- To carry on past failed iterations only up to a budget (e.g. a rollout over many targets), set `skip_failures: true` with `failure_threshold` on the `forloopflow` or `whileloopflow` value: the loop fails with `{ error: { name: "FailureThresholdReached", message } }` once that many iterations have failed. It takes a whole number of at least 1, or an input transform evaluated once when the loop starts that returns one, e.g. `{ type: "javascript", expr: "Math.ceil(flow_input.targets.length * 0.1)" }` for 10%. A parallel loop then cancels the iterations no worker has picked up yet, including those held back by `parallelism`, while iterations already picked up finish, so set `parallelism` to bound how many are in flight when the threshold is reached - When iterations are items a user will look for in a run (customers, files, ids), set `iteration_label` on the `forloopflow` value to a javascript expression naming each one, e.g. `flow_input.iter.value.name`; it only labels iterations in the run viewer and never changes what runs - 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) - `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 @@ -631,4 +632,4 @@ Reference a specific resource using `$res:` prefix: ## OpenFlow Schema -{"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-<type>' (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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this flow does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed, like any failed step."},"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"},"timeout":{"type":"integer","description":"Wall-clock limit in seconds for the whole flow run, counted from its start and including time spent sleeping or suspended at an approval. It also applies when the flow is called as a subflow step, unless that step sets its own timeout, which replaces it. It is checked periodically, so a run can go a few seconds past it. When it expires, the running steps are cancelled, the failure module runs if there is one, and the flow ends cancelled with a timeout error. A calling flow sees the subflow step fail with that error."},"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.<step_id>'"}},"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"},"preview_only":{"type":"boolean","description":"If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run."}}},"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/<flow_path>-<step_id>"},"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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this step does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed."},"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')"},"tag_override":{"type":"string","description":"Override the subflow's worker group tag. Its steps run on this tag unless the subflow sets preserve_step_tags"},"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"},"iteration_label":{"description":"Optional expression evaluated once per iteration into the label the run viewers show for it, e.g. 'flow_input.iter.value.name'. It can reference 'flow_input.iter' and 'results'. Purely informational, a failing expression leaves the iteration unlabelled and never fails it. Labels are capped at 100 characters","$ref":"#/components/schemas/InputTransform"}},"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.<its_own_id>' 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"},"max_iterations":{"type":"integer","minimum":1,"description":"Maximum number of iterations. Checked after each iteration; when reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"},"max_duration_secs":{"type":"integer","minimum":1,"description":"Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"}},"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"},"parallelism":{"description":"Maximum number of branches running at once when parallel=true. Can be static number or expression","$ref":"#/components/schemas/InputTransform"}},"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."},"background":{"type":"boolean","description":"Flowmodule tools only. The agent is answered as soon as the tool's job starts and keeps working; the job's result reaches it in a later message. If the agent finishes its answer first, it stops without holding a worker until the job is done, then continues with the result."},"background_after_secs":{"type":"integer","minimum":1,"description":"Flowmodule tools only, with background unset. The agent waits up to this many seconds for the tool's job and gets its result as usual; a job still running then continues as a background one, its result reaching the agent in a later message."},"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 or Gemini'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: { <question name>: answer },\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\nthe answers, follow it with a branchone whose branch exprs read\nresults.<id>.output.<question>.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"}}}},"continued_on_error":{"type":"array","description":"On a root flow, the steps at any depth that failed and that the flow went past because of continue_on_error (at most 100).","items":{"type":"object","properties":{"id":{"type":"string"},"job":{"type":"string","format":"uuid"}},"required":["id","job"]}},"test_subflows":{"type":"object","description":"In a flow test run, deployed subflow path -> the flow value with the test's step overrides applied, run in place of the deployed subflow.","additionalProperties":{"type":"object"}}},"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_labels":{"type":"array","description":"For a for-loop step whose iteration_label is set, each iteration's label, aligned with flow_jobs. An entry is null when its label evaluated to nothing","items":{"type":"string","nullable":true}},"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","description":"The outcome of each agent action, by position. null while a background tool call is still running.","items":{"type":"boolean","nullable":true}}},"required":["type"]}} \ No newline at end of file +{"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-<type>' (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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this flow does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed, like any failed step."},"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"},"timeout":{"type":"integer","description":"Wall-clock limit in seconds for the whole flow run, counted from its start and including time spent sleeping or suspended at an approval. It also applies when the flow is called as a subflow step, unless that step sets its own timeout, which replaces it. It is checked periodically, so a run can go a few seconds past it. When it expires, the running steps are cancelled, the failure module runs if there is one, and the flow ends cancelled with a timeout error. A calling flow sees the subflow step fail with that error."},"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.<step_id>'"}},"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"},"preview_only":{"type":"boolean","description":"If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run."}}},"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"},"show_on_home":{"type":"boolean","description":"If true, a run waiting on this step is listed on the Home page of each user who can approve it. Leave unset when the approval request is sent through another channel (Slack, Discord, email), so it does not sit there unanswered"}}},"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/<flow_path>-<step_id>"},"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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this step does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed."},"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')"},"tag_override":{"type":"string","description":"Override the subflow's worker group tag. Its steps run on this tag unless the subflow sets preserve_step_tags"},"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"},"failure_threshold":{"description":"With skip_failures, the loop fails with an error named 'FailureThresholdReached' as soon as this many iterations have failed. Static number or expression (e.g. 'Math.ceil(flow_input.targets.length * 0.1)' for a percentage), evaluated once when the loop starts. A sequential loop stops at the iteration that reaches it. A parallel loop cancels the iterations no worker has picked up yet, including those held back by parallelism, while iterations already picked up finish; set parallelism to bound how many are in flight when the threshold is reached","$ref":"#/components/schemas/InputTransform"},"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"},"iteration_label":{"description":"Optional expression evaluated once per iteration into the label the run viewers show for it, e.g. 'flow_input.iter.value.name'. It can reference 'flow_input.iter' and 'results'. Purely informational, a failing expression leaves the iteration unlabelled and never fails it. Labels are capped at 100 characters","$ref":"#/components/schemas/InputTransform"}},"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.<its_own_id>' 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"},"max_iterations":{"type":"integer","minimum":1,"description":"Maximum number of iterations. Checked after each iteration; when reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"},"max_duration_secs":{"type":"integer","minimum":1,"description":"Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"},"failure_threshold":{"description":"With skip_failures, the loop fails with an error named 'FailureThresholdReached' at the iteration that brings the failed iterations to this count. Static number or expression, evaluated once when the loop starts","$ref":"#/components/schemas/InputTransform"}},"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"},"parallelism":{"description":"Maximum number of branches running at once when parallel=true. Can be static number or expression","$ref":"#/components/schemas/InputTransform"}},"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."},"background":{"type":"boolean","description":"Flowmodule tools only. The agent is answered as soon as the tool's job starts and keeps working; the job's result reaches it in a later message. If the agent finishes its answer first, it stops without holding a worker until the job is done, then continues with the result."},"background_after_secs":{"type":"integer","minimum":1,"description":"Flowmodule tools only, with background unset. The agent waits up to this many seconds for the tool's job and gets its result as usual; a job still running then continues as a background one, its result reaching the agent in a later message."},"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 or Gemini'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: { <question name>: answer },\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\nthe answers, follow it with a branchone whose branch exprs read\nresults.<id>.output.<question>.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"}}}},"continued_on_error":{"type":"array","description":"On a root flow, the steps at any depth that failed and that the flow went past because of continue_on_error (at most 100).","items":{"type":"object","properties":{"id":{"type":"string"},"job":{"type":"string","format":"uuid"}},"required":["id","job"]}},"test_subflows":{"type":"object","description":"In a flow test run, deployed subflow path -> the flow value with the test's step overrides applied, run in place of the deployed subflow.","additionalProperties":{"type":"object"}}},"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_labels":{"type":"array","description":"For a for-loop step whose iteration_label is set, each iteration's label, aligned with flow_jobs. An entry is null when its label evaluated to nothing","items":{"type":"string","nullable":true}},"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"},"approved_at":{"type":"string","format":"date-time","description":"absent for approvals recorded before it was kept"},"approved":{"type":"boolean","description":"false for a rejection the flow continued past; absent for approvals recorded before it was kept\n"}},"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","description":"The outcome of each agent action, by position. null while a background tool call is still running.","items":{"type":"boolean","nullable":true}}},"required":["type"]}} \ No newline at end of file diff --git a/system_prompts/auto-generated/prompts.ts b/system_prompts/auto-generated/prompts.ts index 408aef925f..8bc8b7e1da 100644 --- a/system_prompts/auto-generated/prompts.ts +++ b/system_prompts/auto-generated/prompts.ts @@ -344,6 +344,7 @@ can call one, not an agent used as a tool. ## Loop Structure Rules - 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 +- To carry on past failed iterations only up to a budget (e.g. a rollout over many targets), set \`skip_failures: true\` with \`failure_threshold\` on the \`forloopflow\` or \`whileloopflow\` value: the loop fails with \`{ error: { name: "FailureThresholdReached", message } }\` once that many iterations have failed. It takes a whole number of at least 1, or an input transform evaluated once when the loop starts that returns one, e.g. \`{ type: "javascript", expr: "Math.ceil(flow_input.targets.length * 0.1)" }\` for 10%. A parallel loop then cancels the iterations no worker has picked up yet, including those held back by \`parallelism\`, while iterations already picked up finish, so set \`parallelism\` to bound how many are in flight when the threshold is reached - When iterations are items a user will look for in a run (customers, files, ids), set \`iteration_label\` on the \`forloopflow\` value to a javascript expression naming each one, e.g. \`flow_input.iter.value.name\`; it only labels iterations in the run viewer and never changes what runs - 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) - \`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 @@ -1633,7 +1634,7 @@ write a secret you were not given: keep the placeholder. | \`git_sync\` | \`{ repositories: [...] }\`, each with \`git_repo_resource_path\`, \`script_path\` and \`settings\` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. | | \`datatable\` | \`{ datatables: { <name>: { database: { resource_type, resource_path } } } }\`, both required: \`resource_type: postgresql\` with \`resource_path\` a Postgres resource's path, or \`instance\`, or \`external_instance\` (Enterprise only), with \`resource_path\` the name of a database a superadmin set up. A fork's entry can instead be \`{ reference: { workspace_id, datatable } }\`, pointing at its parent's data table; keep it as is. \`main\` is the one scripts use by default. Role permissions are \`datatable_permissions\`. | | \`datatable_permissions\` | \`{ <data table>: { default_role, roles: { <role>: [tenants] } } }\`: who may connect to each data table as which role. Tenants are \`u/<user>\`, \`g/<group>\`, \`f/<folder>\` or \`*\`; \`admin\` is always a role, and \`default_role: null\` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. | -| \`protection_rules\` | \`{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { <role here>: <role in its forks> } } }\`, rules among \`DisableDirectDeployment\`, \`DisableWorkspaceForking\`, \`RestrictDeployToDeployers\`, \`RestrictAnonymousAppDeployment\`, \`RestrictPublicRunSharing\`, \`RestrictGuestAppDeployment\`, \`RequireIsolatedForks\`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | +| \`protection_rules\` | \`{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { <role here>: <role in its forks> } } }\`, rules among \`DisableDirectDeployment\`, \`DisableWorkspaceForking\`, \`RestrictDeployToDeployers\`, \`RestrictAnonymousAppDeployment\`, \`RestrictPublicRunSharing\`, \`RestrictGuestAppDeployment\`, \`RequireIsolatedForks\`, \`RequireSso\` (an account signing in with a password, other than a bypasser, cannot join, and no member can be switched to a password login; members already signing in with a password are not removed). A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | | \`ducklake\` | \`{ ducklakes: { <name>: { catalog, storage, ... } } }\`. | | \`dbt_warehouses\` | dbt warehouse connections. | | \`default_app\` | Path of the app shown as the workspace home. | @@ -1910,6 +1911,15 @@ of the shapes below is shown as JSON. Each shape is an object with that one key (plus \`filename\` for a file, and an optional \`storage\` for \`s3\`). A result carrying any other key beside it is shown as JSON. +## Large results + +A result stored above about 90 KB is not sent with the run: the run page and the editors offer it +as a JSON download, with a Load button that draws it on request. A \`render_all\` lists up to 100 of +its elements with their type and size, counts the rest, and loads them ten at a time. To have a large result previewed without a +click, write the content to the workspace storage and return \`{ "s3": "path/to/key" }\`, which is +previewed by type; for a generated image, also keep it small (a JPEG, or fewer pixels) when it only +needs to be looked at. + ## Choosing one A chart answers a question at a glance: a trend over time (line), a comparison across categories @@ -4110,7 +4120,7 @@ class SqlQuery: export const OPENFLOW_SCHEMA = `## OpenFlow Schema -{"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-<type>' (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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this flow does when its concurrency limit is reached. \`queue\` (default) re-queues it to a later slot, \`fail\` ends it immediately as failed, like any failed step."},"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"},"timeout":{"type":"integer","description":"Wall-clock limit in seconds for the whole flow run, counted from its start and including time spent sleeping or suspended at an approval. It also applies when the flow is called as a subflow step, unless that step sets its own timeout, which replaces it. It is checked periodically, so a run can go a few seconds past it. When it expires, the running steps are cancelled, the failure module runs if there is one, and the flow ends cancelled with a timeout error. A calling flow sees the subflow step fail with that error."},"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.<step_id>'"}},"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"},"preview_only":{"type":"boolean","description":"If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run."}}},"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/<flow_path>-<step_id>"},"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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this step does when its concurrency limit is reached. \`queue\` (default) re-queues it to a later slot, \`fail\` ends it immediately as failed."},"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')"},"tag_override":{"type":"string","description":"Override the subflow's worker group tag. Its steps run on this tag unless the subflow sets preserve_step_tags"},"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"},"iteration_label":{"description":"Optional expression evaluated once per iteration into the label the run viewers show for it, e.g. 'flow_input.iter.value.name'. It can reference 'flow_input.iter' and 'results'. Purely informational, a failing expression leaves the iteration unlabelled and never fails it. Labels are capped at 100 characters","$ref":"#/components/schemas/InputTransform"}},"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.<its_own_id>' 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"},"max_iterations":{"type":"integer","minimum":1,"description":"Maximum number of iterations. Checked after each iteration; when reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"},"max_duration_secs":{"type":"integer","minimum":1,"description":"Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"}},"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"},"parallelism":{"description":"Maximum number of branches running at once when parallel=true. Can be static number or expression","$ref":"#/components/schemas/InputTransform"}},"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."},"background":{"type":"boolean","description":"Flowmodule tools only. The agent is answered as soon as the tool's job starts and keeps working; the job's result reaches it in a later message. If the agent finishes its answer first, it stops without holding a worker until the job is done, then continues with the result."},"background_after_secs":{"type":"integer","minimum":1,"description":"Flowmodule tools only, with background unset. The agent waits up to this many seconds for the tool's job and gets its result as usual; a job still running then continues as a background one, its result reaching the agent in a later message."},"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 or Gemini'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: { <question name>: answer },\\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\\nthe answers, follow it with a branchone whose branch exprs read\\nresults.<id>.output.<question>.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"}}}},"continued_on_error":{"type":"array","description":"On a root flow, the steps at any depth that failed and that the flow went past because of continue_on_error (at most 100).","items":{"type":"object","properties":{"id":{"type":"string"},"job":{"type":"string","format":"uuid"}},"required":["id","job"]}},"test_subflows":{"type":"object","description":"In a flow test run, deployed subflow path -> the flow value with the test's step overrides applied, run in place of the deployed subflow.","additionalProperties":{"type":"object"}}},"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_labels":{"type":"array","description":"For a for-loop step whose iteration_label is set, each iteration's label, aligned with flow_jobs. An entry is null when its label evaluated to nothing","items":{"type":"string","nullable":true}},"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","description":"The outcome of each agent action, by position. null while a background tool call is still running.","items":{"type":"boolean","nullable":true}}},"required":["type"]}}`; +{"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-<type>' (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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this flow does when its concurrency limit is reached. \`queue\` (default) re-queues it to a later slot, \`fail\` ends it immediately as failed, like any failed step."},"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"},"timeout":{"type":"integer","description":"Wall-clock limit in seconds for the whole flow run, counted from its start and including time spent sleeping or suspended at an approval. It also applies when the flow is called as a subflow step, unless that step sets its own timeout, which replaces it. It is checked periodically, so a run can go a few seconds past it. When it expires, the running steps are cancelled, the failure module runs if there is one, and the flow ends cancelled with a timeout error. A calling flow sees the subflow step fail with that error."},"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.<step_id>'"}},"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"},"preview_only":{"type":"boolean","description":"If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run."}}},"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"},"show_on_home":{"type":"boolean","description":"If true, a run waiting on this step is listed on the Home page of each user who can approve it. Leave unset when the approval request is sent through another channel (Slack, Discord, email), so it does not sit there unanswered"}}},"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/<flow_path>-<step_id>"},"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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this step does when its concurrency limit is reached. \`queue\` (default) re-queues it to a later slot, \`fail\` ends it immediately as failed."},"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')"},"tag_override":{"type":"string","description":"Override the subflow's worker group tag. Its steps run on this tag unless the subflow sets preserve_step_tags"},"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"},"failure_threshold":{"description":"With skip_failures, the loop fails with an error named 'FailureThresholdReached' as soon as this many iterations have failed. Static number or expression (e.g. 'Math.ceil(flow_input.targets.length * 0.1)' for a percentage), evaluated once when the loop starts. A sequential loop stops at the iteration that reaches it. A parallel loop cancels the iterations no worker has picked up yet, including those held back by parallelism, while iterations already picked up finish; set parallelism to bound how many are in flight when the threshold is reached","$ref":"#/components/schemas/InputTransform"},"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"},"iteration_label":{"description":"Optional expression evaluated once per iteration into the label the run viewers show for it, e.g. 'flow_input.iter.value.name'. It can reference 'flow_input.iter' and 'results'. Purely informational, a failing expression leaves the iteration unlabelled and never fails it. Labels are capped at 100 characters","$ref":"#/components/schemas/InputTransform"}},"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.<its_own_id>' 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"},"max_iterations":{"type":"integer","minimum":1,"description":"Maximum number of iterations. Checked after each iteration; when reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"},"max_duration_secs":{"type":"integer","minimum":1,"description":"Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"},"failure_threshold":{"description":"With skip_failures, the loop fails with an error named 'FailureThresholdReached' at the iteration that brings the failed iterations to this count. Static number or expression, evaluated once when the loop starts","$ref":"#/components/schemas/InputTransform"}},"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"},"parallelism":{"description":"Maximum number of branches running at once when parallel=true. Can be static number or expression","$ref":"#/components/schemas/InputTransform"}},"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."},"background":{"type":"boolean","description":"Flowmodule tools only. The agent is answered as soon as the tool's job starts and keeps working; the job's result reaches it in a later message. If the agent finishes its answer first, it stops without holding a worker until the job is done, then continues with the result."},"background_after_secs":{"type":"integer","minimum":1,"description":"Flowmodule tools only, with background unset. The agent waits up to this many seconds for the tool's job and gets its result as usual; a job still running then continues as a background one, its result reaching the agent in a later message."},"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 or Gemini'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: { <question name>: answer },\\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\\nthe answers, follow it with a branchone whose branch exprs read\\nresults.<id>.output.<question>.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"}}}},"continued_on_error":{"type":"array","description":"On a root flow, the steps at any depth that failed and that the flow went past because of continue_on_error (at most 100).","items":{"type":"object","properties":{"id":{"type":"string"},"job":{"type":"string","format":"uuid"}},"required":["id","job"]}},"test_subflows":{"type":"object","description":"In a flow test run, deployed subflow path -> the flow value with the test's step overrides applied, run in place of the deployed subflow.","additionalProperties":{"type":"object"}}},"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_labels":{"type":"array","description":"For a for-loop step whose iteration_label is set, each iteration's label, aligned with flow_jobs. An entry is null when its label evaluated to nothing","items":{"type":"string","nullable":true}},"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"},"approved_at":{"type":"string","format":"date-time","description":"absent for approvals recorded before it was kept"},"approved":{"type":"boolean","description":"false for a rejection the flow continued past; absent for approvals recorded before it was kept\\n"}},"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","description":"The outcome of each agent action, by position. null while a background tool call is still running.","items":{"type":"boolean","nullable":true}}},"required":["type"]}}`; export const CLI_COMMANDS = `# Windmill CLI Commands @@ -4146,12 +4156,14 @@ app related commands - \`--host <host:string>\` - Host to bind the dev server to - \`--entry <entry:string>\` - Entry point file (default: index.ts for Svelte, index.tsx otherwise) - \`--no-open\` - Don't automatically open the browser + - \`--run-install-scripts\` - Run the dependencies' lifecycle scripts when installing node_modules - \`--recording\` - Frame the app in a shell with a Record button, to capture a replayable session recording of the app under development - \`app lint [app_folder:string]\` - Lint a raw app folder to validate structure and buildability - \`--fix\` - Attempt to fix common issues (not implemented yet) - \`app bundle [app_folder:string]\` - Bundle a raw app folder to js/css without deploying it - \`--out <dir:string>\` - Directory to write bundle.js and bundle.css into (default: <app_folder>/dist) - \`--no-minify\` - Skip minification + - \`--run-install-scripts\` - Run the dependencies' lifecycle scripts when installing node_modules - \`app new\` - create a new raw app from a template - \`--summary <summary:string>\` - App summary (short description). Skips the prompt when provided. Triggers non-interactive mode. - \`--path <path:string>\` - App path (e.g., f/folder/my_app or u/username/my_app). Skips the prompt when provided. Triggers non-interactive mode. @@ -4239,6 +4251,7 @@ Watch local file changes and live-reload the dev page for preview. Does NOT depl - \`--proxy-port <port:number>\` - Port for a localhost reverse proxy to the remote Windmill server - \`--path <path:string>\` - Watch a specific windmill path (e.g., u/admin/my_script or f/my_flow) - \`--no-open\` - Do not open the browser automatically +- \`--host <host:string>\` - Address to bind the dev server to: a loopback address or 0.0.0.0 for every interface (default: 127.0.0.1, this machine only) ### digest @@ -4439,6 +4452,7 @@ sync local with a remote instance or the opposite (push or pull) - \`--dry-run\` - Perform a dry run without making changes - \`--skip-users\` - Skip pulling users - \`--skip-settings\` - Skip pulling settings + - \`--show-secrets\` - Pull secrets (license key, passwords, tokens) in clear instead of redacted - \`--skip-configs\` - Skip pulling configs (worker groups) - \`--skip-groups\` - Skip pulling instance groups - \`--include-workspaces\` - Also pull workspaces @@ -4461,7 +4475,7 @@ sync local with a remote instance or the opposite (push or pull) - \`instance whoami\` - Display information about the currently logged-in user - \`instance get-config\` - Dump the current instance config (global settings + worker configs) as YAML - \`-o, --output-file <file:string>\` - Write YAML to a file instead of stdout - - \`--show-secrets\` - Include sensitive fields (license key, JWT secret) without prompting + - \`--show-secrets\` - Include secrets (license key, passwords, tokens) in clear without prompting - \`--instance <instance:string>\` - Name of the instance, override the active instance - \`instance connect-slack\` - Non-interactively connect Slack at the instance level using a pre-minted bot token (xoxb-...). Produces the same artifacts as the UI OAuth flow: global_settings 'slack' row + encrypted f/slack_bot/global_bot_token variable and resource in the admins workspace. - \`--bot-token <bot_token:string>\` - Slack bot token (xoxb-...) @@ -4814,6 +4828,13 @@ Manage API tokens - \`token create\` - Create a new API token - \`--label <label:string>\` - Token label - \`--expiration <expiration:string>\` - Token expiration (ISO 8601 timestamp) + - \`--all-workspaces\` - Do not bind the token to the current workspace: it then reaches every workspace you are a member of and instance-level endpoints + - \`--admin\` - Carry your workspace admin rights (off by default) + - \`--superadmin\` - Carry your superadmin rights (off by default) + - \`--scope <scope:string>\` - Restrict the token to this scope (e.g. jobs:run, scripts:read:f/folder/*). Repeatable. Omit for no scope restriction. +- \`token update-scopes <token_prefix:string>\` - Replace the scopes of one of your tokens, by its prefix + - \`--scope <scope:string>\` - Scope the token is restricted to (e.g. jobs:run, scripts:read:f/folder/*). Repeatable; replaces all existing scopes. + - \`--clear\` - Remove every scope restriction (the token keeps its workspace binding and admin/superadmin rights) - \`token delete <token_prefix:string>\` - Delete a token by its prefix ### trash @@ -4873,6 +4894,8 @@ user related commands - \`user create-token\` - Create a new API token for the authenticated user - \`--email <email:string>\` - Specify credentials to use for authentication. This will not be stored. It will only be used to exchange for a token with the API server, which will not be stored either. - \`--password <password:string>\` - Specify credentials to use for authentication. This will not be stored. It will only be used to exchange for a token with the API server, which will not be stored either. + - \`--admin\` - Carry your workspace admin rights (off by default) + - \`--superadmin\` - Carry your superadmin rights (off by default) ### variable diff --git a/system_prompts/auto-generated/skills/cli-commands/SKILL.md b/system_prompts/auto-generated/skills/cli-commands/SKILL.md index 87691caffb..b0d3cf7ae5 100644 --- a/system_prompts/auto-generated/skills/cli-commands/SKILL.md +++ b/system_prompts/auto-generated/skills/cli-commands/SKILL.md @@ -37,12 +37,14 @@ app related commands - `--host <host:string>` - Host to bind the dev server to - `--entry <entry:string>` - Entry point file (default: index.ts for Svelte, index.tsx otherwise) - `--no-open` - Don't automatically open the browser + - `--run-install-scripts` - Run the dependencies' lifecycle scripts when installing node_modules - `--recording` - Frame the app in a shell with a Record button, to capture a replayable session recording of the app under development - `app lint [app_folder:string]` - Lint a raw app folder to validate structure and buildability - `--fix` - Attempt to fix common issues (not implemented yet) - `app bundle [app_folder:string]` - Bundle a raw app folder to js/css without deploying it - `--out <dir:string>` - Directory to write bundle.js and bundle.css into (default: <app_folder>/dist) - `--no-minify` - Skip minification + - `--run-install-scripts` - Run the dependencies' lifecycle scripts when installing node_modules - `app new` - create a new raw app from a template - `--summary <summary:string>` - App summary (short description). Skips the prompt when provided. Triggers non-interactive mode. - `--path <path:string>` - App path (e.g., f/folder/my_app or u/username/my_app). Skips the prompt when provided. Triggers non-interactive mode. @@ -130,6 +132,7 @@ Watch local file changes and live-reload the dev page for preview. Does NOT depl - `--proxy-port <port:number>` - Port for a localhost reverse proxy to the remote Windmill server - `--path <path:string>` - Watch a specific windmill path (e.g., u/admin/my_script or f/my_flow) - `--no-open` - Do not open the browser automatically +- `--host <host:string>` - Address to bind the dev server to: a loopback address or 0.0.0.0 for every interface (default: 127.0.0.1, this machine only) ### digest @@ -330,6 +333,7 @@ sync local with a remote instance or the opposite (push or pull) - `--dry-run` - Perform a dry run without making changes - `--skip-users` - Skip pulling users - `--skip-settings` - Skip pulling settings + - `--show-secrets` - Pull secrets (license key, passwords, tokens) in clear instead of redacted - `--skip-configs` - Skip pulling configs (worker groups) - `--skip-groups` - Skip pulling instance groups - `--include-workspaces` - Also pull workspaces @@ -352,7 +356,7 @@ sync local with a remote instance or the opposite (push or pull) - `instance whoami` - Display information about the currently logged-in user - `instance get-config` - Dump the current instance config (global settings + worker configs) as YAML - `-o, --output-file <file:string>` - Write YAML to a file instead of stdout - - `--show-secrets` - Include sensitive fields (license key, JWT secret) without prompting + - `--show-secrets` - Include secrets (license key, passwords, tokens) in clear without prompting - `--instance <instance:string>` - Name of the instance, override the active instance - `instance connect-slack` - Non-interactively connect Slack at the instance level using a pre-minted bot token (xoxb-...). Produces the same artifacts as the UI OAuth flow: global_settings 'slack' row + encrypted f/slack_bot/global_bot_token variable and resource in the admins workspace. - `--bot-token <bot_token:string>` - Slack bot token (xoxb-...) @@ -705,6 +709,13 @@ Manage API tokens - `token create` - Create a new API token - `--label <label:string>` - Token label - `--expiration <expiration:string>` - Token expiration (ISO 8601 timestamp) + - `--all-workspaces` - Do not bind the token to the current workspace: it then reaches every workspace you are a member of and instance-level endpoints + - `--admin` - Carry your workspace admin rights (off by default) + - `--superadmin` - Carry your superadmin rights (off by default) + - `--scope <scope:string>` - Restrict the token to this scope (e.g. jobs:run, scripts:read:f/folder/*). Repeatable. Omit for no scope restriction. +- `token update-scopes <token_prefix:string>` - Replace the scopes of one of your tokens, by its prefix + - `--scope <scope:string>` - Scope the token is restricted to (e.g. jobs:run, scripts:read:f/folder/*). Repeatable; replaces all existing scopes. + - `--clear` - Remove every scope restriction (the token keeps its workspace binding and admin/superadmin rights) - `token delete <token_prefix:string>` - Delete a token by its prefix ### trash @@ -764,6 +775,8 @@ user related commands - `user create-token` - Create a new API token for the authenticated user - `--email <email:string>` - Specify credentials to use for authentication. This will not be stored. It will only be used to exchange for a token with the API server, which will not be stored either. - `--password <password:string>` - Specify credentials to use for authentication. This will not be stored. It will only be used to exchange for a token with the API server, which will not be stored either. + - `--admin` - Carry your workspace admin rights (off by default) + - `--superadmin` - Carry your superadmin rights (off by default) ### variable diff --git a/system_prompts/auto-generated/skills/rich-results/SKILL.md b/system_prompts/auto-generated/skills/rich-results/SKILL.md index ec49550773..8c73970720 100644 --- a/system_prompts/auto-generated/skills/rich-results/SKILL.md +++ b/system_prompts/auto-generated/skills/rich-results/SKILL.md @@ -30,6 +30,15 @@ of the shapes below is shown as JSON. Each shape is an object with that one key (plus `filename` for a file, and an optional `storage` for `s3`). A result carrying any other key beside it is shown as JSON. +## Large results + +A result stored above about 90 KB is not sent with the run: the run page and the editors offer it +as a JSON download, with a Load button that draws it on request. A `render_all` lists up to 100 of +its elements with their type and size, counts the rest, and loads them ten at a time. To have a large result previewed without a +click, write the content to the workspace storage and return `{ "s3": "path/to/key" }`, which is +previewed by type; for a generated image, also keep it small (a JPEG, or fewer pixels) when it only +needs to be looked at. + ## Choosing one A chart answers a question at a glance: a trend over time (line), a comparison across categories diff --git a/system_prompts/auto-generated/skills/workspace-settings/SKILL.md b/system_prompts/auto-generated/skills/workspace-settings/SKILL.md index 3554c8195e..6fbff099fc 100644 --- a/system_prompts/auto-generated/skills/workspace-settings/SKILL.md +++ b/system_prompts/auto-generated/skills/workspace-settings/SKILL.md @@ -47,7 +47,7 @@ write a secret you were not given: keep the placeholder. | `git_sync` | `{ repositories: [...] }`, each with `git_repo_resource_path`, `script_path` and `settings` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. | | `datatable` | `{ datatables: { <name>: { database: { resource_type, resource_path } } } }`, both required: `resource_type: postgresql` with `resource_path` a Postgres resource's path, or `instance`, or `external_instance` (Enterprise only), with `resource_path` the name of a database a superadmin set up. A fork's entry can instead be `{ reference: { workspace_id, datatable } }`, pointing at its parent's data table; keep it as is. `main` is the one scripts use by default. Role permissions are `datatable_permissions`. | | `datatable_permissions` | `{ <data table>: { default_role, roles: { <role>: [tenants] } } }`: who may connect to each data table as which role. Tenants are `u/<user>`, `g/<group>`, `f/<folder>` or `*`; `admin` is always a role, and `default_role: null` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. | -| `protection_rules` | `{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { <role here>: <role in its forks> } } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | +| `protection_rules` | `{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { <role here>: <role in its forks> } } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`, `RequireSso` (an account signing in with a password, other than a bypasser, cannot join, and no member can be switched to a password login; members already signing in with a password are not removed). A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | | `ducklake` | `{ ducklakes: { <name>: { catalog, storage, ... } } }`. | | `dbt_warehouses` | dbt warehouse connections. | | `default_app` | Path of the app shown as the workspace home. | diff --git a/system_prompts/auto-generated/skills/write-flow/SKILL.md b/system_prompts/auto-generated/skills/write-flow/SKILL.md index d275ec03ac..599f39eb9d 100644 --- a/system_prompts/auto-generated/skills/write-flow/SKILL.md +++ b/system_prompts/auto-generated/skills/write-flow/SKILL.md @@ -402,6 +402,7 @@ can call one, not an agent used as a tool. ## Loop Structure Rules - 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 +- To carry on past failed iterations only up to a budget (e.g. a rollout over many targets), set `skip_failures: true` with `failure_threshold` on the `forloopflow` or `whileloopflow` value: the loop fails with `{ error: { name: "FailureThresholdReached", message } }` once that many iterations have failed. It takes a whole number of at least 1, or an input transform evaluated once when the loop starts that returns one, e.g. `{ type: "javascript", expr: "Math.ceil(flow_input.targets.length * 0.1)" }` for 10%. A parallel loop then cancels the iterations no worker has picked up yet, including those held back by `parallelism`, while iterations already picked up finish, so set `parallelism` to bound how many are in flight when the threshold is reached - When iterations are items a user will look for in a run (customers, files, ids), set `iteration_label` on the `forloopflow` value to a javascript expression naming each one, e.g. `flow_input.iter.value.name`; it only labels iterations in the run viewer and never changes what runs - 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) - `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 @@ -719,4 +720,4 @@ Reference a specific resource using `$res:` prefix: ## OpenFlow Schema -{"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-<type>' (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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this flow does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed, like any failed step."},"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"},"timeout":{"type":"integer","description":"Wall-clock limit in seconds for the whole flow run, counted from its start and including time spent sleeping or suspended at an approval. It also applies when the flow is called as a subflow step, unless that step sets its own timeout, which replaces it. It is checked periodically, so a run can go a few seconds past it. When it expires, the running steps are cancelled, the failure module runs if there is one, and the flow ends cancelled with a timeout error. A calling flow sees the subflow step fail with that error."},"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.<step_id>'"}},"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"},"preview_only":{"type":"boolean","description":"If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run."}}},"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/<flow_path>-<step_id>"},"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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this step does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed."},"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')"},"tag_override":{"type":"string","description":"Override the subflow's worker group tag. Its steps run on this tag unless the subflow sets preserve_step_tags"},"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"},"iteration_label":{"description":"Optional expression evaluated once per iteration into the label the run viewers show for it, e.g. 'flow_input.iter.value.name'. It can reference 'flow_input.iter' and 'results'. Purely informational, a failing expression leaves the iteration unlabelled and never fails it. Labels are capped at 100 characters","$ref":"#/components/schemas/InputTransform"}},"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.<its_own_id>' 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"},"max_iterations":{"type":"integer","minimum":1,"description":"Maximum number of iterations. Checked after each iteration; when reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"},"max_duration_secs":{"type":"integer","minimum":1,"description":"Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"}},"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"},"parallelism":{"description":"Maximum number of branches running at once when parallel=true. Can be static number or expression","$ref":"#/components/schemas/InputTransform"}},"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."},"background":{"type":"boolean","description":"Flowmodule tools only. The agent is answered as soon as the tool's job starts and keeps working; the job's result reaches it in a later message. If the agent finishes its answer first, it stops without holding a worker until the job is done, then continues with the result."},"background_after_secs":{"type":"integer","minimum":1,"description":"Flowmodule tools only, with background unset. The agent waits up to this many seconds for the tool's job and gets its result as usual; a job still running then continues as a background one, its result reaching the agent in a later message."},"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 or Gemini'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: { <question name>: answer },\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\nthe answers, follow it with a branchone whose branch exprs read\nresults.<id>.output.<question>.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"}}}},"continued_on_error":{"type":"array","description":"On a root flow, the steps at any depth that failed and that the flow went past because of continue_on_error (at most 100).","items":{"type":"object","properties":{"id":{"type":"string"},"job":{"type":"string","format":"uuid"}},"required":["id","job"]}},"test_subflows":{"type":"object","description":"In a flow test run, deployed subflow path -> the flow value with the test's step overrides applied, run in place of the deployed subflow.","additionalProperties":{"type":"object"}}},"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_labels":{"type":"array","description":"For a for-loop step whose iteration_label is set, each iteration's label, aligned with flow_jobs. An entry is null when its label evaluated to nothing","items":{"type":"string","nullable":true}},"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","description":"The outcome of each agent action, by position. null while a background tool call is still running.","items":{"type":"boolean","nullable":true}}},"required":["type"]}} +{"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-<type>' (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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this flow does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed, like any failed step."},"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"},"timeout":{"type":"integer","description":"Wall-clock limit in seconds for the whole flow run, counted from its start and including time spent sleeping or suspended at an approval. It also applies when the flow is called as a subflow step, unless that step sets its own timeout, which replaces it. It is checked periodically, so a run can go a few seconds past it. When it expires, the running steps are cancelled, the failure module runs if there is one, and the flow ends cancelled with a timeout error. A calling flow sees the subflow step fail with that error."},"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.<step_id>'"}},"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"},"preview_only":{"type":"boolean","description":"If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run."}}},"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"},"show_on_home":{"type":"boolean","description":"If true, a run waiting on this step is listed on the Home page of each user who can approve it. Leave unset when the approval request is sent through another channel (Slack, Discord, email), so it does not sit there unanswered"}}},"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/<flow_path>-<step_id>"},"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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this step does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed."},"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')"},"tag_override":{"type":"string","description":"Override the subflow's worker group tag. Its steps run on this tag unless the subflow sets preserve_step_tags"},"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"},"failure_threshold":{"description":"With skip_failures, the loop fails with an error named 'FailureThresholdReached' as soon as this many iterations have failed. Static number or expression (e.g. 'Math.ceil(flow_input.targets.length * 0.1)' for a percentage), evaluated once when the loop starts. A sequential loop stops at the iteration that reaches it. A parallel loop cancels the iterations no worker has picked up yet, including those held back by parallelism, while iterations already picked up finish; set parallelism to bound how many are in flight when the threshold is reached","$ref":"#/components/schemas/InputTransform"},"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"},"iteration_label":{"description":"Optional expression evaluated once per iteration into the label the run viewers show for it, e.g. 'flow_input.iter.value.name'. It can reference 'flow_input.iter' and 'results'. Purely informational, a failing expression leaves the iteration unlabelled and never fails it. Labels are capped at 100 characters","$ref":"#/components/schemas/InputTransform"}},"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.<its_own_id>' 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"},"max_iterations":{"type":"integer","minimum":1,"description":"Maximum number of iterations. Checked after each iteration; when reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"},"max_duration_secs":{"type":"integer","minimum":1,"description":"Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"},"failure_threshold":{"description":"With skip_failures, the loop fails with an error named 'FailureThresholdReached' at the iteration that brings the failed iterations to this count. Static number or expression, evaluated once when the loop starts","$ref":"#/components/schemas/InputTransform"}},"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"},"parallelism":{"description":"Maximum number of branches running at once when parallel=true. Can be static number or expression","$ref":"#/components/schemas/InputTransform"}},"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."},"background":{"type":"boolean","description":"Flowmodule tools only. The agent is answered as soon as the tool's job starts and keeps working; the job's result reaches it in a later message. If the agent finishes its answer first, it stops without holding a worker until the job is done, then continues with the result."},"background_after_secs":{"type":"integer","minimum":1,"description":"Flowmodule tools only, with background unset. The agent waits up to this many seconds for the tool's job and gets its result as usual; a job still running then continues as a background one, its result reaching the agent in a later message."},"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 or Gemini'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: { <question name>: answer },\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\nthe answers, follow it with a branchone whose branch exprs read\nresults.<id>.output.<question>.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"}}}},"continued_on_error":{"type":"array","description":"On a root flow, the steps at any depth that failed and that the flow went past because of continue_on_error (at most 100).","items":{"type":"object","properties":{"id":{"type":"string"},"job":{"type":"string","format":"uuid"}},"required":["id","job"]}},"test_subflows":{"type":"object","description":"In a flow test run, deployed subflow path -> the flow value with the test's step overrides applied, run in place of the deployed subflow.","additionalProperties":{"type":"object"}}},"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_labels":{"type":"array","description":"For a for-loop step whose iteration_label is set, each iteration's label, aligned with flow_jobs. An entry is null when its label evaluated to nothing","items":{"type":"string","nullable":true}},"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"},"approved_at":{"type":"string","format":"date-time","description":"absent for approvals recorded before it was kept"},"approved":{"type":"boolean","description":"false for a rejection the flow continued past; absent for approvals recorded before it was kept\n"}},"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","description":"The outcome of each agent action, by position. null while a background tool call is still running.","items":{"type":"boolean","nullable":true}}},"required":["type"]}} diff --git a/system_prompts/base/display-results.md b/system_prompts/base/display-results.md index 17f0c5b864..aa82751ddb 100644 --- a/system_prompts/base/display-results.md +++ b/system_prompts/base/display-results.md @@ -25,6 +25,15 @@ of the shapes below is shown as JSON. Each shape is an object with that one key (plus `filename` for a file, and an optional `storage` for `s3`). A result carrying any other key beside it is shown as JSON. +## Large results + +A result stored above about 90 KB is not sent with the run: the run page and the editors offer it +as a JSON download, with a Load button that draws it on request. A `render_all` lists up to 100 of +its elements with their type and size, counts the rest, and loads them ten at a time. To have a large result previewed without a +click, write the content to the workspace storage and return `{ "s3": "path/to/key" }`, which is +previewed by type; for a generated image, also keep it small (a JPEG, or fewer pixels) when it only +needs to be looked at. + ## Choosing one A chart answers a question at a glance: a trend over time (line), a comparison across categories diff --git a/system_prompts/base/flow-base.md b/system_prompts/base/flow-base.md index 275497a828..99079a5312 100644 --- a/system_prompts/base/flow-base.md +++ b/system_prompts/base/flow-base.md @@ -320,6 +320,7 @@ can call one, not an agent used as a tool. ## Loop Structure Rules - 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 +- To carry on past failed iterations only up to a budget (e.g. a rollout over many targets), set `skip_failures: true` with `failure_threshold` on the `forloopflow` or `whileloopflow` value: the loop fails with `{ error: { name: "FailureThresholdReached", message } }` once that many iterations have failed. It takes a whole number of at least 1, or an input transform evaluated once when the loop starts that returns one, e.g. `{ type: "javascript", expr: "Math.ceil(flow_input.targets.length * 0.1)" }` for 10%. A parallel loop then cancels the iterations no worker has picked up yet, including those held back by `parallelism`, while iterations already picked up finish, so set `parallelism` to bound how many are in flight when the threshold is reached - When iterations are items a user will look for in a run (customers, files, ids), set `iteration_label` on the `forloopflow` value to a javascript expression naming each one, e.g. `flow_input.iter.value.name`; it only labels iterations in the run viewer and never changes what runs - 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) - `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 diff --git a/system_prompts/base/workspace-settings.md b/system_prompts/base/workspace-settings.md index cdc80dd692..d37a501ff9 100644 --- a/system_prompts/base/workspace-settings.md +++ b/system_prompts/base/workspace-settings.md @@ -42,7 +42,7 @@ write a secret you were not given: keep the placeholder. | `git_sync` | `{ repositories: [...] }`, each with `git_repo_resource_path`, `script_path` and `settings` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. | | `datatable` | `{ datatables: { <name>: { database: { resource_type, resource_path } } } }`, both required: `resource_type: postgresql` with `resource_path` a Postgres resource's path, or `instance`, or `external_instance` (Enterprise only), with `resource_path` the name of a database a superadmin set up. A fork's entry can instead be `{ reference: { workspace_id, datatable } }`, pointing at its parent's data table; keep it as is. `main` is the one scripts use by default. Role permissions are `datatable_permissions`. | | `datatable_permissions` | `{ <data table>: { default_role, roles: { <role>: [tenants] } } }`: who may connect to each data table as which role. Tenants are `u/<user>`, `g/<group>`, `f/<folder>` or `*`; `admin` is always a role, and `default_role: null` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. | -| `protection_rules` | `{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { <role here>: <role in its forks> } } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | +| `protection_rules` | `{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { <role here>: <role in its forks> } } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`, `RequireSso` (an account signing in with a password, other than a bypasser, cannot join, and no member can be switched to a password login; members already signing in with a password are not removed). A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | | `ducklake` | `{ ducklakes: { <name>: { catalog, storage, ... } } }`. | | `dbt_warehouses` | dbt warehouse connections. | | `default_app` | Path of the app shown as the workspace home. | diff --git a/typescript-client/build.jsr.sh b/typescript-client/build.jsr.sh index 41a8eac37e..d1ebb31cc1 100755 --- a/typescript-client/build.jsr.sh +++ b/typescript-client/build.jsr.sh @@ -11,6 +11,7 @@ sed -i 's/get \[Symbol\.toStringTag\]() {/get \[Symbol\.toStringTag\]() : string cp "${script_dirpath}/client.ts" "${script_dirpath}/src/" cp "${script_dirpath}/wacError.ts" "${script_dirpath}/src/" +cp "${script_dirpath}/taskParams.ts" "${script_dirpath}/src/" cp "${script_dirpath}/s3Types.ts" "${script_dirpath}/src/" cp "${script_dirpath}/sqlUtils.ts" "${script_dirpath}/src/" # Two JSR-only rules, enforced by `jsr publish` (which publish.jsr.sh runs diff --git a/typescript-client/build.sh b/typescript-client/build.sh index 57734362ef..3894d0aba8 100755 --- a/typescript-client/build.sh +++ b/typescript-client/build.sh @@ -41,6 +41,7 @@ fi cp "${script_dirpath}/client.ts" "${script_dirpath}/src/" cp "${script_dirpath}/wacError.ts" "${script_dirpath}/src/" +cp "${script_dirpath}/taskParams.ts" "${script_dirpath}/src/" cp "${script_dirpath}/s3Types.ts" "${script_dirpath}/src/" cp "${script_dirpath}/sqlUtils.ts" "${script_dirpath}/src/" echo "" >> "${script_dirpath}/src/index.ts" diff --git a/typescript-client/client.ts b/typescript-client/client.ts index 1b0a8123cc..00a8fe047b 100644 --- a/typescript-client/client.ts +++ b/typescript-client/client.ts @@ -14,6 +14,7 @@ import { import type { Retry } from "./types.gen"; import { OpenAPI } from "./core/OpenAPI"; import { isSuspendSignal, stepErrorMarker, taskErrorFromMarker } from "./wacError"; +import { getParamNames } from "./taskParams"; // import type { DenoS3LightClientSettings } from "./index"; import { DenoS3LightClientSettings, @@ -365,49 +366,6 @@ export async function cancelJob( }); } -const STRIP_COMMENTS = - /(\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s*=[^,\)]*(('(?:\\'|[^'\r\n])*')|("(?:\\"|[^"\r\n])*"))|(\s*=[^,\)]*))/gm; -function getParamNames(func: Function): string[] { - const fnStr = func.toString().replace(STRIP_COMMENTS, ""); - // Find the matching closing paren for the parameter list, handling nesting - const openIdx = fnStr.indexOf("("); - if (openIdx === -1) return []; - let depth = 1; - let closeIdx = openIdx + 1; - for (; closeIdx < fnStr.length && depth > 0; closeIdx++) { - if (fnStr[closeIdx] === "(") depth++; - else if (fnStr[closeIdx] === ")") depth--; - } - const paramStr = fnStr.slice(openIdx + 1, closeIdx - 1).trim(); - if (!paramStr) return []; - // Split on commas at depth 0 (skip nested parens, angle brackets, braces) - const params: string[] = []; - let current = ""; - let d = 0; - for (const ch of paramStr) { - if ("(<{".includes(ch)) d++; - else if (")>}".includes(ch)) d--; - if (ch === "," && d === 0) { - params.push(current.trim()); - current = ""; - } else { - current += ch; - } - } - if (current.trim()) params.push(current.trim()); - // Extract the parameter name from each param (strip type annotations, destructuring, rest) - return params.map((p) => { - // Remove rest operator - p = p.replace(/^\.\.\./, ""); - // For destructured params like { url, depth }: Config, use a positional fallback - if (p.startsWith("{") || p.startsWith("[")) return ""; - // Strip type annotation (e.g. "x: number" -> "x", "x?: string" -> "x") - const colonIdx = p.indexOf(":"); - if (colonIdx !== -1) p = p.slice(0, colonIdx); - return p.replace(/\?$/, "").trim(); - }).filter(Boolean); -} - /** * @deprecated Use runScriptByPathAsync or runScriptByHashAsync instead */ @@ -2565,7 +2523,7 @@ export function task<T extends (...args: any[]) => Promise<any>>( return (async () => { const paramNames = getParamNames(fn); const kwargs: Record<string, any> = {}; - args.forEach((x, i) => (kwargs[paramNames[i]] = x)); + args.forEach((x, i) => (kwargs[paramNames[i] || `arg${i}`] = x)); let req = await fetch( `${OpenAPI.BASE}/w/${getWorkspace()}/jobs/run/workflow_as_code/${getEnv( "WM_JOB_ID" diff --git a/typescript-client/jsr.json b/typescript-client/jsr.json index 36bbfb5a2d..cc3c137c4b 100644 --- a/typescript-client/jsr.json +++ b/typescript-client/jsr.json @@ -1,9 +1,9 @@ { "name": "@windmill/windmill", - "version": "1.884.1", + "version": "1.894.1", "exports": "./src/index.ts", "publish": { - "exclude": ["!src", "./s3Types.ts", "./sqlUtils.ts", "./client.ts", "./wacError.ts"] + "exclude": ["!src", "./s3Types.ts", "./sqlUtils.ts", "./client.ts", "./wacError.ts", "./taskParams.ts"] }, "license": "Apache-2.0" } diff --git a/typescript-client/package.json b/typescript-client/package.json index f6ad0a6798..519357529d 100644 --- a/typescript-client/package.json +++ b/typescript-client/package.json @@ -1,7 +1,7 @@ { "name": "windmill-client", "description": "Windmill SDK client for browsers and Node.js", - "version": "1.884.1", + "version": "1.894.1", "author": "Ruben Fiszel", "license": "Apache 2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/typescript-client#readme", diff --git a/typescript-client/taskParams.ts b/typescript-client/taskParams.ts new file mode 100644 index 0000000000..94db65d46c --- /dev/null +++ b/typescript-client/taskParams.ts @@ -0,0 +1,134 @@ +// A name (any Unicode identifier) or a number literal, read as one token. +const WORD = /^(?:[\p{ID_Start}$_][\p{ID_Continue}$‌‍]*|0[xXoObB][\da-fA-F_]+n?|\d[\d_]*(?:\.[\d_]*)?(?:[eE][+-]?\d+)?n?|\.\d[\d_]*(?:[eE][+-]?\d+)?)/u; +const REGEX_AFTER_KEYWORD = new Set([ + "return", "typeof", "instanceof", "in", "new", "delete", "void", "throw", + "case", "do", "else", "yield", "await", +]); + +/** + * The source of a function's parameter list, with comments removed and every string, + * template and regular expression literal replaced by `""`, so that none of their + * characters can open, close or split the list. + */ +function parameterListSource(src: string): string | undefined { + let out = ""; + let depth = 0; + // Whether a `/` here starts a regular expression rather than a division. + let regexAllowed = true; + let i = 0; + while (i < src.length) { + const ch = src[i]; + const next = src[i + 1]; + if (ch === "/" && next === "/") { + const end = src.indexOf("\n", i); + i = end === -1 ? src.length : end; + continue; + } + if (ch === "/" && next === "*") { + const end = src.indexOf("*/", i + 2); + i = end === -1 ? src.length : end + 2; + continue; + } + if (ch === "'" || ch === '"' || ch === "`") { + i = skipQuoted(src, i, ch); + if (depth > 0) out += '""'; + regexAllowed = false; + continue; + } + if (ch === "/" && regexAllowed) { + i = skipRegex(src, i); + if (depth > 0) out += '""'; + regexAllowed = false; + continue; + } + const word = WORD.exec(src.slice(i, i + 256))?.[0]; + if (word) { + if (depth > 0) out += word; + // A `/` after a name or a number divides, except after a keyword that starts an + // expression (`return /x/`). + regexAllowed = REGEX_AFTER_KEYWORD.has(word) && !/\.\s*$/.test(src.slice(Math.max(0, i - 64), i)); + i += word.length; + continue; + } + if (ch === "(") { + if (depth > 0) out += ch; + depth++; + } else if (ch === ")") { + depth--; + if (depth === 0) return out; + if (depth > 0) out += ch; + } else if (depth > 0) { + out += ch; + } + if (!/\s/.test(ch)) { + // After a closing bracket or a postfix `++`/`--` a `/` divides; after any other + // punctuator (an operator, `(`, `,`, `=`, `[`, `{`) it starts a regular expression. + const postfix = (ch === "+" || ch === "-") && src[i - 1] === ch; + regexAllowed = !postfix && !/[)\]}]/.test(ch); + } + i++; + } + return undefined; +} + +function skipQuoted(src: string, start: number, quote: string): number { + let i = start + 1; + while (i < src.length && src[i] !== quote) { + if (src[i] === "\\") i++; + else if (quote !== "`" && src[i] === "\n") break; + i++; + } + return i + 1; +} + +function skipRegex(src: string, start: number): number { + let i = start + 1; + let inClass = false; + while (i < src.length && src[i] !== "\n") { + const ch = src[i]; + if (ch === "\\") i++; + else if (ch === "[") inClass = true; + else if (ch === "]") inClass = false; + else if (ch === "/" && !inClass) break; + i++; + } + i++; + while (i < src.length && /[a-z]/i.test(src[i])) i++; + return i; +} + +/** + * The names a v1 task job binds its arguments by, in order: the script parser names an + * object pattern `anon<N>`, and an array pattern has no name (`""`). + * @internal + */ +export function getParamNames(func: Function): string[] { + const paramStr = parameterListSource(func.toString())?.trim(); + if (!paramStr) return []; + // Split on commas at depth 0 (skip nested parens, brackets, braces) + const params: string[] = []; + let current = ""; + let d = 0; + for (const ch of paramStr) { + if ("({[".includes(ch)) d++; + else if (")}]".includes(ch)) d--; + if (ch === "," && d === 0) { + params.push(current.trim()); + current = ""; + } else { + current += ch; + } + } + if (current.trim()) params.push(current.trim()); + let anon = 0; + return params.map((p) => { + p = p.replace(/^\.\.\./, ""); + if (p.startsWith("{")) return `anon${++anon}`; + if (p.startsWith("[")) return ""; + p = p.split("=")[0]; + // Strip type annotation (e.g. "x: number" -> "x", "x?: string" -> "x") + const colonIdx = p.indexOf(":"); + if (colonIdx !== -1) p = p.slice(0, colonIdx); + return p.replace(/\?$/, "").trim(); + }); +} diff --git a/typescript-client/tests/task_params.test.ts b/typescript-client/tests/task_params.test.ts new file mode 100644 index 0000000000..f3e3ef95a5 --- /dev/null +++ b/typescript-client/tests/task_params.test.ts @@ -0,0 +1,63 @@ +/** + * Run with: bun test typescript-client/tests/task_params.test.ts + */ +import { expect, test } from "bun:test"; +import { getParamNames } from "../taskParams"; + +const cases: [string, Function, string[]][] = [ + // @ts-ignore + ["plain", async function f(a, b) {}, ["a", "b"]], + // @ts-ignore + ["string default with separators", async function f(a = "x,)(", b) {}, ["a", "b"]], + // @ts-ignore + ["template default", async function f(a = `,)`, b) {}, ["a", "b"]], + // @ts-ignore + ["regex default with a paren", async function f(p = /\(/, b) {}, ["p", "b"]], + // @ts-ignore + ["regex default with a class", async function f(p = /[(]/, b) {}, ["p", "b"]], + // @ts-ignore + ["regex default ending in a slash", async function f(p = /\//, url) {}, ["p", "url"]], + // @ts-ignore + ["regex default with flags", async function f(p = /a,b/gi, b) {}, ["p", "b"]], + // @ts-ignore + ["division in a default", async function f(a = 4 / 2, b = (1) / 2, c) {}, ["a", "b", "c"]], + // @ts-ignore + ["regex after a keyword in a default", async function f(v = (() => { return /a+/.test("a"); })(), s) {}, ["v", "s"]], + [ + "division after a unicode name and numbers", + // Evaluated from a string: the test transpiler would rewrite the source. + (0, eval)("(async function f(é = 1, a = é / 2, b = 1. / 2, c = 0x1f / 2, d) {})"), + ["é", "a", "b", "c", "d"], + ], + // @ts-ignore + ["division after a keyword-named property", async function f(a = ({ in: 4 }).in / 2, of = 1, b = of / 2, c) {}, ["a", "of", "b", "c"]], + // @ts-ignore + ["division after a postfix operator", async function f(a, b = a++ / 2, c = a-- / 2, d) {}, ["a", "b", "c", "d"]], + // @ts-ignore + ["object pattern", async function f({ x, y }, b) {}, ["anon1", "b"]], + // @ts-ignore + ["array pattern", async function f([x], b) {}, ["", "b"]], + // @ts-ignore + [ + "comments", + // @ts-ignore + async function f(a /* , ) */, // ) + b) {}, + ["a", "b"], + ], + // @ts-ignore + ["arrow", async (a, b = [1, 2]) => {}, ["a", "b"]], + // @ts-ignore + ["rest", async function f(a, ...rest) {}, ["a", "rest"]], +]; + +for (const [name, fn, expected] of cases) { + test(name, () => { + expect(getParamNames(fn)).toEqual(expected); + }); +} + +test("parenthesis in a regex inside the body is not read as the list", () => { + // @ts-ignore + expect(getParamNames(async function f(a) { return /\)/.test(a); })).toEqual(["a"]); +}); diff --git a/version.txt b/version.txt index 2b25752d80..577ffe58b0 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.884.1 +1.894.1 diff --git a/windmill-yaml-validator/package-lock.json b/windmill-yaml-validator/package-lock.json index af40b2ff17..4da9a39a00 100644 --- a/windmill-yaml-validator/package-lock.json +++ b/windmill-yaml-validator/package-lock.json @@ -1,12 +1,12 @@ { "name": "windmill-yaml-validator", - "version": "1.884.1", + "version": "1.894.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "windmill-yaml-validator", - "version": "1.884.1", + "version": "1.894.1", "license": "Apache 2.0", "dependencies": { "@stoplight/yaml": "^4.3.0", diff --git a/windmill-yaml-validator/package.json b/windmill-yaml-validator/package.json index ef186976f8..f80ecff785 100644 --- a/windmill-yaml-validator/package.json +++ b/windmill-yaml-validator/package.json @@ -1,6 +1,6 @@ { "name": "windmill-yaml-validator", - "version": "1.884.1", + "version": "1.894.1", "description": "YAML validator for Windmill flow, schedule, and trigger files", "main": "dist/index.js", "types": "dist/index.d.ts",