diff --git a/.agents/skills/pr/SKILL.md b/.agents/skills/pr/SKILL.md index f2a9ec8dad..e83dca2b84 100644 --- a/.agents/skills/pr/SKILL.md +++ b/.agents/skills/pr/SKILL.md @@ -135,7 +135,7 @@ sufficient — see "Flip, or ask first" below. The one standing exception is an leave that PR in draft (usually so it can be tested first) — honour it for that PR, and don't carry it over to the next one. -1. **Trigger a round and wait for it**: launch the waiter as a background Bash task (a round takes 10–30 min; you are woken when it exits — do not stop the session or poll in the foreground while it runs): +1. **Trigger a round and wait for it**: launch the waiter as a background Bash task (a round takes about 10 min, 20 at most; you are woken when it exits — do not stop the session or poll in the foreground while it runs): ```bash bash .agents/skills/pr/review-round.sh @@ -143,6 +143,11 @@ carry it over to the next one. It comments `/review` on the PR — which runs the Codex, Claude and Pi CI reviewers even on a draft — waits for the spawned `PR Review Commands` workflow run(s) to complete, then prints one verdict line per reviewer and saves the full review comments to files. + Waiting rules — a session that breaks one sits idle on results the user can already see: + - **Use the waiter, not a loop of your own.** It always exits: as soon as the Codex, Claude and Pi verdicts are posted, once the round's run completes (failed jobs included), at a 20-minute deadline with whatever was posted, or non-zero when no run appeared or GitHub kept erroring — treat a non-zero exit as "look yourself", not "no reviews". A hand-written loop waiting for "a comment from each reviewer" never ends when one reviewer dies (capacity errors, cancelled jobs), since a dead job posts nothing. + - **If your harness does not wake you when a background command exits, run the waiter in the foreground** with a timeout of at least 25 minutes. Backgrounding it and ending your turn then means nobody ever reads the result. + - **Act on a missing reviewer immediately.** Reviewers that never start or hang are common. The waiter names each reviewer with no review and the jobs that did not finish cleanly; re-trigger each missing one at once with a `/codex`, `/claude` or `/pi` PR comment and run the waiter again, rather than waiting longer. + `/review` (and `/codex`) are **idempotent per head SHA**: if a running or successful review already covers the current head, they skip that agent and post nothing new — the waiter reads the existing verdict for that head, so a skipped agent is *not* a missing one. A cancelled/failed head run is re-run in place; a fresh run is launched only when nothing covers the head. So an unchanged-head re-review is a near no-op, not a new round — push a commit to get genuinely fresh reviews. 2. **Judge the round.** Codex is mandatory; Claude, Pi and cubic count whenever they posted. Every review starts with one of the three `REVIEW.md` verdicts: diff --git a/.agents/skills/pr/review-round.sh b/.agents/skills/pr/review-round.sh index abd94005f6..adc7c72214 100755 --- a/.agents/skills/pr/review-round.sh +++ b/.agents/skills/pr/review-round.sh @@ -7,19 +7,20 @@ # Comments `/review` on the PR (works on drafts), waits for the spawned # "PR Review Commands" workflow run(s) to complete, then prints one verdict # line per reviewer and saves each full review comment to a file. A round -# takes 10-30 minutes: run this in the background and act on its output when +# takes about 10 minutes, 20 at most: run this in the background and act on its output when # it exits, per the pr skill ("Review rounds"). set -euo pipefail REPO=${REPO:-$(gh repo view --json nameWithOwner --jq .nameWithOwner)} PR=${1:-$(gh pr view --json number --jq .number)} +PR_TITLE=$(gh pr view "$PR" --repo "$REPO" --json title --jq .title) # Timestamp of the trigger comment, straight from GitHub, so local clock skew # can't make the run/comment filters below miss part of the round. TRIGGER_TIME=$(gh api "repos/$REPO/issues/$PR/comments" -f body='/review' --jq .created_at) echo "Review round triggered on $REPO#$PR at $TRIGGER_TIME" -# Retry wrapper for one-off gh/API hiccups: a 45-minute wait must not die on +# Retry wrapper for one-off gh/API hiccups: a 20-minute wait must not die on # a single transient failure. retry() { local attempt @@ -31,21 +32,39 @@ retry() { } # The /review comment spawns one "PR Review Commands" run holding the -# claude/codex/pi jobs. Runs aren't linked to a PR, so wait on every run of -# that workflow created after the trigger: a concurrent round on another PR -# can only delay the answer, never truncate it. Every issue comment on any PR -# spawns a fast-completing parse run of the same workflow, so the round's own -# run may briefly lag the listing while unrelated runs already show completed: -# require the all-completed state to hold past a floor and across two -# consecutive polls before trusting it. -DEADLINE=$(( $(date +%s) + 45 * 60 )) +# claude/codex/pi jobs. Runs aren't linked to a PR, but an issue_comment run's +# display title is the PR's title: match on it, since waiting on every run +# after the trigger means a stuck reviewer on any other PR holds this round +# to the deadline. Every comment on this PR (the reviewers' own +# included) spawns a fast-completing parse run, so the round's own run may +# briefly lag the listing while those already show completed: require the +# all-completed state to hold past a floor and across two consecutive polls. +# +# Reviews land 6-10 minutes in. A reviewer that never starts or hangs is common +# and only a human re-trigger fixes it, so stop early: as soon as all three +# verdicts are posted, else at 20 minutes, naming the jobs still unfinished. +VERDICT_RE='(Good to merge|Mergeable, but should ideally address nits|Should address issues before merging)' +# Claude edits a placeholder comment in place, hence updated_at. +all_verdicts_in() { + gh api "repos/$REPO/issues/$PR/comments?per_page=100" --paginate 2>/dev/null \ + | jq -s -e --arg t "$TRIGGER_TIME" --arg re "$VERDICT_RE" ' + [.[][] | select(.updated_at > $t) | select(.body // "" | test($re))] as $c + | ($c | any(.user.login == "github-actions[bot]" and (.body | startswith("## Codex Review")))) + and ($c | any(.user.login == "github-actions[bot]" and (.body | startswith("## Pi Review")))) + and ($c | any(.user.login == "claude[bot]"))' >/dev/null +} +DEADLINE=$(( $(date +%s) + 20 * 60 )) NO_RUN_DEADLINE=$(( $(date +%s) + 5 * 60 )) MIN_WAIT_UNTIL=$(( $(date +%s) + 3 * 60 )) STABLE=0 +SEEN=0 +ALL_IN=0 +ROUND_RUNS='[]' FAILURES=0 while :; do if RUNS=$(gh run list --repo "$REPO" --workflow=pr-review-commands.yml \ - --created ">=$TRIGGER_TIME" --limit 100 --json status); then + --created ">=$TRIGGER_TIME" --limit 500 --json databaseId,status,displayTitle \ + --jq "[.[] | select(.displayTitle == $(jq -Rn --arg t "$PR_TITLE" '$t'))]"); then FAILURES=0 else FAILURES=$(( FAILURES + 1 )) @@ -58,6 +77,13 @@ while :; do continue fi TOTAL=$(jq length <<<"$RUNS") + # The limit applies before the title filter, so on a busy repo this PR's run + # can age out of the listing: once seen, never report it as missing. + if [ "$TOTAL" -gt 0 ]; then SEEN=1; ROUND_RUNS=$RUNS; fi + if all_verdicts_in; then + ALL_IN=1 + break + fi PENDING=$(jq '[.[] | select(.status != "completed")] | length' <<<"$RUNS") NOW=$(date +%s) if [ "$TOTAL" -gt 0 ] && [ "$PENDING" -eq 0 ] && [ "$NOW" -gt "$MIN_WAIT_UNTIL" ]; then @@ -68,12 +94,12 @@ while :; do else STABLE=0 fi - if [ "$TOTAL" -eq 0 ] && [ "$NOW" -gt "$NO_RUN_DEADLINE" ]; then + if [ "$SEEN" -eq 0 ] && [ "$NOW" -gt "$NO_RUN_DEADLINE" ]; then echo "ERROR: no 'PR Review Commands' run appeared within 5 minutes of the /review comment; check that the comment author has write access and the workflow is enabled." >&2 exit 1 fi if [ "$NOW" -gt "$DEADLINE" ]; then - echo "WARNING: review round still pending after 45 minutes; reporting whatever has been posted so far." >&2 + echo "WARNING: review round still pending after 20 minutes; reporting whatever has been posted so far." >&2 break fi sleep 60 @@ -100,7 +126,7 @@ head_run_state() { # A re-run-in-place review lands on a head-tied run that finishes after the fast # pr-review-commands run, so let those settle before reading verdicts. for wf in codex-pr-review.yml pi-pr-review.yml pr-ready-review.yml; do - while :; do + while [ "$ALL_IN" -eq 0 ]; do case "$(head_run_state "$wf")" in ""|"completed "*) break ;; *) if [ "$(date +%s)" -gt "$DEADLINE" ]; then break; fi; sleep 30 ;; @@ -121,8 +147,6 @@ REVIEWS_RAW=$(retry gh api "repos/$REPO/pulls/$PR/reviews?per_page=100" --pagina jq -s --arg t "$TRIGGER_TIME" '[.[][] | select((.submitted_at // "") > $t)]' \ <<<"$REVIEWS_RAW" > "$OUT_DIR/pr-reviews.json" -VERDICT_RE='(Good to merge|Mergeable, but should ideally address nits|Should address issues before merging)' - body_by_header() { # jq -r --arg h "$2" '[.[] | select(.body // "" | contains($h))] | last | .body // empty' "$1" } @@ -144,7 +168,11 @@ verdict_body() { # report() { # local name=$1 body=$2 verdict if [ -z "$body" ]; then - echo "$name: (no review posted for this head)" + if [ "$name" = cubic ]; then + echo "$name: (no review posted for this head)" + else + echo "$name: (no review posted for this head; re-trigger now with a '/$name' PR comment)" + fi return fi printf '%s\n' "$body" > "$OUT_DIR/$name.md" @@ -167,6 +195,17 @@ fi report cubic "$CUBIC_BODY" echo echo "Full round output: $OUT_DIR (comments.json, pr-reviews.json, one .md per reviewer)" +if [ "$ALL_IN" -eq 0 ]; then + UNFINISHED=$(for id in $(jq -r '.[].databaseId' <<<"$ROUND_RUNS"); do + gh run view "$id" --repo "$REPO" --json jobs --jq '.jobs[] + | select(.status != "completed" or (.conclusion | IN("success", "skipped") | not)) + | " \(.name): \(.status) \(.conclusion // "") since \(.startedAt // "-")"' 2>/dev/null || true + done) + if [ -n "$UNFINISHED" ]; then + echo "Review jobs that did not finish cleanly:" + printf '%s\n' "$UNFINISHED" + fi +fi if [ -z "$CODEX_BODY" ]; then echo "WARNING: no Codex verdict for $HEAD_SHA - its head run is not green (cancelled/failed/absent, not merely skipped-because-already-reviewed). Re-trigger with a '/codex' PR comment (re-runs the interrupted run in place, or launches one) and wait again." >&2 fi diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 427fbc10c0..d28fa6134c 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.884.1" + ".": "1.885.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e66471050..0d6c2c9362 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,31 @@ # Changelog +## [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/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-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-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-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-18d01ba5fb5a25984ae1291b7c20820613f4dd8cd03186b17e595f538a4d4397.json b/backend/.sqlx/query-18d01ba5fb5a25984ae1291b7c20820613f4dd8cd03186b17e595f538a4d4397.json new file mode 100644 index 0000000000..3ceaafdbcb --- /dev/null +++ b/backend/.sqlx/query-18d01ba5fb5a25984ae1291b7c20820613f4dd8cd03186b17e595f538a4d4397.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\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": "18d01ba5fb5a25984ae1291b7c20820613f4dd8cd03186b17e595f538a4d4397" +} 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-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-26f1b3af9057517b82a3c263e0396ee2747445e2a66381ed1b9fd96e0d9909bb.json b/backend/.sqlx/query-26f1b3af9057517b82a3c263e0396ee2747445e2a66381ed1b9fd96e0d9909bb.json new file mode 100644 index 0000000000..725d75aee1 --- /dev/null +++ b/backend/.sqlx/query-26f1b3af9057517b82a3c263e0396ee2747445e2a66381ed1b9fd96e0d9909bb.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\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": "26f1b3af9057517b82a3c263e0396ee2747445e2a66381ed1b9fd96e0d9909bb" +} 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-44ad516d89eeb5411cbd34a839c4c6eab6782b23eb8d7f8831b2f0e9f9c17055.json b/backend/.sqlx/query-44ad516d89eeb5411cbd34a839c4c6eab6782b23eb8d7f8831b2f0e9f9c17055.json new file mode 100644 index 0000000000..974782f017 --- /dev/null +++ b/backend/.sqlx/query-44ad516d89eeb5411cbd34a839c4c6eab6782b23eb8d7f8831b2f0e9f9c17055.json @@ -0,0 +1,35 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO audit_partitioned\n (workspace_id, username, operation, action_kind, resource, parameters, email, span,\n client_ip, user_agent)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Varchar", + { + "Custom": { + "name": "action_kind", + "kind": { + "Enum": [ + "create", + "update", + "delete", + "execute" + ] + } + } + }, + "Varchar", + "Jsonb", + "Varchar", + "Varchar", + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "44ad516d89eeb5411cbd34a839c4c6eab6782b23eb8d7f8831b2f0e9f9c17055" +} 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-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-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-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-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-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-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/Cargo.lock b/backend/Cargo.lock index c01150d464..2a6e93941c 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -77,9 +77,9 @@ dependencies = [ [[package]] name = "ahash" -version = "0.8.13" +version = "0.8.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fca89247609239eeb6915e6991111866b92d7b31025e69302bbf430cc4d2c38" +checksum = "54dae3d1d7b8956f3506c4e999a74e77f932a59153ccf38ab8cf96db74bb9dc0" dependencies = [ "cfg-if", "const-random", @@ -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.14", "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.14", "arrow-array", "arrow-buffer", "arrow-data", @@ -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", ] @@ -3430,7 +3430,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.14", "arrow", "arrow-ipc", "base64 0.22.1", @@ -3670,7 +3670,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.14", "arrow", "datafusion-common", "datafusion-doc", @@ -3691,7 +3691,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.14", "arrow", "datafusion-common", "datafusion-expr-common", @@ -3798,7 +3798,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.14", "arrow", "datafusion-common", "datafusion-expr", @@ -3820,7 +3820,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.14", "arrow", "datafusion-common", "datafusion-expr-common", @@ -3853,7 +3853,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.14", "arrow", "arrow-ord", "arrow-schema", @@ -5073,7 +5073,7 @@ dependencies = [ "curve25519-dalek 5.0.0", "ed25519 3.0.0", "serde", - "sha2 0.11.1", + "sha2 0.11.2", "signature 3.0.0", "subtle", "zeroize", @@ -6292,7 +6292,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.14", "allocator-api2", ] @@ -7659,7 +7659,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.14", "async-broadcast", "async-stream", "backon", @@ -9465,7 +9465,7 @@ dependencies = [ "elliptic-curve 0.14.3", "primefield", "primeorder 0.14.0", - "sha2 0.11.1", + "sha2 0.11.2", ] [[package]] @@ -9491,7 +9491,7 @@ dependencies = [ "fiat-crypto 0.3.0", "primefield", "primeorder 0.14.0", - "sha2 0.11.1", + "sha2 0.11.2", ] [[package]] @@ -9552,7 +9552,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.14", "arrow-array", "arrow-buffer", "arrow-cast", @@ -10101,7 +10101,7 @@ dependencies = [ "md-5 0.11.0", "memchr", "rand 0.10.4", - "sha2 0.11.1", + "sha2 0.11.2", "stringprep", ] @@ -10215,7 +10215,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]] @@ -12392,9 +12392,9 @@ dependencies = [ [[package]] name = "sha2" -version = "0.11.1" +version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27" dependencies = [ "cfg-if", "cpufeatures 0.3.1", @@ -12771,7 +12771,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 +12783,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 +12821,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 +12833,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 +12857,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 +12901,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 +12941,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 +14482,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 +14494,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 +15654,7 @@ dependencies = [ [[package]] name = "windmill" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-nats", @@ -15744,7 +15744,7 @@ dependencies = [ [[package]] name = "windmill-ai" -version = "1.884.1" +version = "1.885.0" dependencies = [ "async-stream", "async-trait", @@ -15779,7 +15779,7 @@ dependencies = [ [[package]] name = "windmill-alerting" -version = "1.884.1" +version = "1.885.0" dependencies = [ "axum", "chrono", @@ -15792,7 +15792,7 @@ dependencies = [ [[package]] name = "windmill-api" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "argon2", @@ -15934,7 +15934,7 @@ dependencies = [ [[package]] name = "windmill-api-agent-workers" -version = "1.884.1" +version = "1.885.0" dependencies = [ "axum", "chrono", @@ -15958,7 +15958,7 @@ dependencies = [ [[package]] name = "windmill-api-assets" -version = "1.884.1" +version = "1.885.0" dependencies = [ "axum", "chrono", @@ -15975,7 +15975,7 @@ dependencies = [ [[package]] name = "windmill-api-auth" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "axum", @@ -16002,7 +16002,7 @@ dependencies = [ [[package]] name = "windmill-api-client" -version = "1.884.1" +version = "1.885.0" dependencies = [ "reqwest 0.12.28", "serde", @@ -16012,7 +16012,7 @@ dependencies = [ [[package]] name = "windmill-api-configs" -version = "1.884.1" +version = "1.885.0" dependencies = [ "axum", "chrono", @@ -16029,7 +16029,7 @@ dependencies = [ [[package]] name = "windmill-api-debug" -version = "1.884.1" +version = "1.885.0" dependencies = [ "axum", "base64 0.22.1", @@ -16051,7 +16051,7 @@ dependencies = [ [[package]] name = "windmill-api-embeddings" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "axum", @@ -16074,7 +16074,7 @@ dependencies = [ [[package]] name = "windmill-api-flow-conversations" -version = "1.884.1" +version = "1.885.0" dependencies = [ "axum", "chrono", @@ -16090,7 +16090,7 @@ dependencies = [ [[package]] name = "windmill-api-flows" -version = "1.884.1" +version = "1.885.0" dependencies = [ "axum", "chrono", @@ -16112,7 +16112,7 @@ dependencies = [ [[package]] name = "windmill-api-groups" -version = "1.884.1" +version = "1.885.0" dependencies = [ "axum", "chrono", @@ -16134,7 +16134,7 @@ dependencies = [ [[package]] name = "windmill-api-inputs" -version = "1.884.1" +version = "1.885.0" dependencies = [ "axum", "chrono", @@ -16148,7 +16148,7 @@ dependencies = [ [[package]] name = "windmill-api-integration-tests" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-nats", @@ -16184,7 +16184,7 @@ dependencies = [ [[package]] name = "windmill-api-jobs" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "axum", @@ -16210,7 +16210,7 @@ dependencies = [ [[package]] name = "windmill-api-npm-proxy" -version = "1.884.1" +version = "1.885.0" dependencies = [ "axum", "chrono", @@ -16238,7 +16238,7 @@ dependencies = [ [[package]] name = "windmill-api-openapi" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "axum", @@ -16260,7 +16260,7 @@ dependencies = [ [[package]] name = "windmill-api-schedule" -version = "1.884.1" +version = "1.885.0" dependencies = [ "axum", "chrono", @@ -16279,7 +16279,7 @@ dependencies = [ [[package]] name = "windmill-api-scripts" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "axum", @@ -16321,7 +16321,7 @@ dependencies = [ [[package]] name = "windmill-api-settings" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "axum", @@ -16352,7 +16352,7 @@ dependencies = [ [[package]] name = "windmill-api-sse" -version = "1.884.1" +version = "1.885.0" dependencies = [ "lazy_static", "serde", @@ -16364,7 +16364,7 @@ dependencies = [ [[package]] name = "windmill-api-users" -version = "1.884.1" +version = "1.885.0" dependencies = [ "argon2", "axum", @@ -16388,7 +16388,7 @@ dependencies = [ [[package]] name = "windmill-api-workers" -version = "1.884.1" +version = "1.885.0" dependencies = [ "axum", "chrono", @@ -16403,7 +16403,7 @@ dependencies = [ [[package]] name = "windmill-api-workspaces" -version = "1.884.1" +version = "1.885.0" dependencies = [ "axum", "chrono", @@ -16442,7 +16442,7 @@ dependencies = [ [[package]] name = "windmill-audit" -version = "1.884.1" +version = "1.885.0" dependencies = [ "chrono", "lazy_static", @@ -16457,7 +16457,7 @@ dependencies = [ [[package]] name = "windmill-autoscaling" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "axum", @@ -16476,7 +16476,7 @@ dependencies = [ [[package]] name = "windmill-common" -version = "1.884.1" +version = "1.885.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -16530,6 +16530,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 +16546,7 @@ dependencies = [ "rand 0.9.5", "rcgen", "regex", + "reqwest 0.12.28", "reqwest 0.13.5", "reqwest-middleware", "reqwest-retry", @@ -16595,7 +16597,7 @@ dependencies = [ [[package]] name = "windmill-dep-map" -version = "1.884.1" +version = "1.885.0" dependencies = [ "chrono", "futures", @@ -16615,7 +16617,7 @@ dependencies = [ [[package]] name = "windmill-git-sync" -version = "1.884.1" +version = "1.885.0" dependencies = [ "regex", "serde", @@ -16632,7 +16634,7 @@ dependencies = [ [[package]] name = "windmill-indexer" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "astral-tokio-tar", @@ -16659,7 +16661,7 @@ dependencies = [ [[package]] name = "windmill-jseval" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "futures", @@ -16676,7 +16678,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.884.1" +version = "1.885.0" dependencies = [ "itertools 0.14.0", "lazy_static", @@ -16692,7 +16694,7 @@ dependencies = [ [[package]] name = "windmill-mcp" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-trait", @@ -16714,7 +16716,7 @@ dependencies = [ [[package]] name = "windmill-native-triggers" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-trait", @@ -16746,7 +16748,7 @@ dependencies = [ [[package]] name = "windmill-oauth" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "arc-swap", @@ -16771,7 +16773,7 @@ dependencies = [ [[package]] name = "windmill-object-store" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-stream", @@ -16807,7 +16809,7 @@ dependencies = [ [[package]] name = "windmill-operator" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "futures", @@ -16826,7 +16828,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.884.1" +version = "1.885.0" dependencies = [ "convert_case 0.6.0", "serde", @@ -16835,7 +16837,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "lazy_static", @@ -16847,7 +16849,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "serde_json", @@ -16859,7 +16861,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "gosyn", @@ -16871,7 +16873,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "lazy_static", @@ -16883,7 +16885,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "serde_json", @@ -16895,7 +16897,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "nu-parser", @@ -16906,7 +16908,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16917,7 +16919,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16929,7 +16931,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16940,7 +16942,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-recursion", @@ -16963,7 +16965,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "serde_json", @@ -16975,7 +16977,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "lazy_static", @@ -16989,7 +16991,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -17006,7 +17008,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "lazy_static", @@ -17019,7 +17021,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "serde", @@ -17031,7 +17033,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "lazy_static", @@ -17049,7 +17051,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -17065,7 +17067,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -17082,7 +17084,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "lazy_static", @@ -17096,7 +17098,7 @@ dependencies = [ [[package]] name = "windmill-queue" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-recursion", @@ -17134,7 +17136,7 @@ dependencies = [ [[package]] name = "windmill-runtime-nativets" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "const_format", @@ -17172,7 +17174,7 @@ dependencies = [ [[package]] name = "windmill-sql-datatype-parser-wasm" -version = "1.884.1" +version = "1.885.0" dependencies = [ "getrandom 0.3.4", "wasm-bindgen", @@ -17183,7 +17185,7 @@ dependencies = [ [[package]] name = "windmill-store" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-recursion", @@ -17218,7 +17220,7 @@ dependencies = [ [[package]] name = "windmill-test-utils" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-trait", @@ -17242,7 +17244,7 @@ dependencies = [ [[package]] name = "windmill-trigger" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-trait", @@ -17275,7 +17277,7 @@ dependencies = [ [[package]] name = "windmill-trigger-amqp" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-trait", @@ -17302,7 +17304,7 @@ dependencies = [ [[package]] name = "windmill-trigger-azure" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-trait", @@ -17335,7 +17337,7 @@ dependencies = [ [[package]] name = "windmill-trigger-email" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-trait", @@ -17355,7 +17357,7 @@ dependencies = [ [[package]] name = "windmill-trigger-gcp" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-trait", @@ -17389,7 +17391,7 @@ dependencies = [ [[package]] name = "windmill-trigger-http" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-trait", @@ -17426,7 +17428,7 @@ dependencies = [ [[package]] name = "windmill-trigger-kafka" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-trait", @@ -17449,7 +17451,7 @@ dependencies = [ [[package]] name = "windmill-trigger-mqtt" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-trait", @@ -17473,7 +17475,7 @@ dependencies = [ [[package]] name = "windmill-trigger-nats" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-nats", @@ -17497,7 +17499,7 @@ dependencies = [ [[package]] name = "windmill-trigger-postgres" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-trait", @@ -17532,7 +17534,7 @@ dependencies = [ [[package]] name = "windmill-trigger-sqs" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-trait", @@ -17560,7 +17562,7 @@ dependencies = [ [[package]] name = "windmill-trigger-websocket" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-trait", @@ -17586,7 +17588,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -17606,7 +17608,7 @@ dependencies = [ [[package]] name = "windmill-worker" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-once-cell", @@ -17724,7 +17726,7 @@ dependencies = [ [[package]] name = "windmill-worker-volumes" -version = "1.884.1" +version = "1.885.0" dependencies = [ "bytes", "fs4", @@ -18522,18 +18524,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..e8f206883e 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "windmill" -version = "1.884.1" +version = "1.885.0" 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.885.0" 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/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/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..47b988f014 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.885.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -6430,7 +6430,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.884.1" +version = "1.885.0" dependencies = [ "proc-macro2", "quote", @@ -6442,7 +6442,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.884.1" +version = "1.885.0" dependencies = [ "convert_case", "serde", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "lazy_static", @@ -6463,7 +6463,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "serde_json", @@ -6475,7 +6475,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "gosyn", @@ -6487,7 +6487,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "lazy_static", @@ -6499,7 +6499,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "serde_json", @@ -6511,7 +6511,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "nu-parser", @@ -6522,7 +6522,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6533,7 +6533,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6545,7 +6545,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6556,7 +6556,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "async-recursion", @@ -6579,7 +6579,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "serde_json", @@ -6591,7 +6591,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "lazy_static", @@ -6605,7 +6605,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "convert_case", @@ -6622,7 +6622,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "lazy_static", @@ -6635,7 +6635,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "serde", @@ -6647,7 +6647,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "lazy_static", @@ -6665,7 +6665,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -6681,7 +6681,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6698,7 +6698,7 @@ dependencies = [ [[package]] name = "windmill-parser-wasm" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -6730,7 +6730,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "lazy_static", @@ -6744,7 +6744,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.884.1" +version = "1.885.0" dependencies = [ "anyhow", "bitflags", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index d06a874c26..98bdf00ccd 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.885.0" edition = "2021" authors = ["Ruben Fiszel "] diff --git a/backend/src/monitor.rs b/backend/src/monitor.rs index 05bdbc3163..34b4edfd3c 100644 --- a/backend/src/monitor.rs +++ b/backend/src/monitor.rs @@ -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::{ @@ -802,6 +802,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 +846,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 +907,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"); 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/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/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/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/windmill-api-auth/src/auth.rs b/backend/windmill-api-auth/src/auth.rs index 889f1f09a0..32b31f771a 100644 --- a/backend/windmill-api-auth/src/auth.rs +++ b/backend/windmill-api-auth/src/auth.rs @@ -41,6 +41,8 @@ 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); } /// A token keeps its identity when a superadmin moves the account to another address, so entries @@ -956,6 +958,69 @@ 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) +} + pub(crate) async fn extract_token(parts: &mut Parts, state: &S) -> Option { let auth_header = parts .headers @@ -965,14 +1030,21 @@ 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); + 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()) + }) + } + } }; #[derive(Deserialize)] diff --git a/backend/windmill-api-auth/src/lib.rs b/backend/windmill-api-auth/src/lib.rs index 640c05623b..070ff51dda 100644 --- a/backend/windmill-api-auth/src/lib.rs +++ b/backend/windmill-api-auth/src/lib.rs @@ -462,6 +462,24 @@ where Ok(()) } +/// 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 diff --git a/backend/windmill-api-auth/src/scopes.rs b/backend/windmill-api-auth/src/scopes.rs index 2dffbeca51..9247411bb2 100644 --- a/backend/windmill-api-auth/src/scopes.rs +++ b/backend/windmill-api-auth/src/scopes.rs @@ -348,7 +348,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; 34] = [ "jobs_u/get_flow/", "jobs_u/get_root_job_id/", "jobs_u/get/", @@ -377,6 +377,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/", @@ -575,7 +576,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; 27] = [ "jobs_u/get/", "jobs_u/get_logs/", "jobs_u/get_completed_logs_tail/", @@ -595,6 +596,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/", 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/operator_builder_flows.rs b/backend/windmill-api-integration-tests/tests/operator_builder_flows.rs index 6bed27eca5..e204ab8e52 100644 --- a/backend/windmill-api-integration-tests/tests/operator_builder_flows.rs +++ b/backend/windmill-api-integration-tests/tests/operator_builder_flows.rs @@ -1,7 +1,10 @@ use serde_json::json; +use serial_test::serial; use sqlx::{Pool, Postgres}; use windmill_test_utils::*; +/// Every test here must be `#[serial]`: the rights cache is process-global and keyed by workspace id +/// alone, so parallel tests under this same id read each other's rights. const WS: &str = "test-workspace"; fn operator_client() -> reqwest::Client { @@ -82,6 +85,7 @@ fn inline_code_flow(path: &str) -> serde_json::Value { /// already deployed and nothing more, and the endpoints that author code stay shut whether or not /// it is granted. #[sqlx::test(migrations = "../migrations", fixtures("base", "permissions_test"))] +#[serial] async fn test_operator_builder_flows_boundary(db: Pool) -> anyhow::Result<()> { initialize_tracing().await; let server = ApiServer::start(db.clone()).await?; @@ -477,3 +481,49 @@ async fn check_builder_agents( Ok(()) } + +/// Each slot of a flow picks scripts of its own kind. A role without `code` gets the kind it asks +/// for, preprocessors without a main included, and still no library. +#[sqlx::test(migrations = "../migrations", fixtures("base", "permissions_test"))] +#[serial] +async fn test_operator_lists_scripts_of_the_requested_kind( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let api = format!("http://localhost:{port}/api/w/{WS}"); + let c = operator_client(); + + add_script(&db, 5001, "u/operator/action", "operator").await?; + add_script(&db, 5002, "u/operator/library", "operator").await?; + add_script(&db, 5003, "u/operator/prep", "operator").await?; + sqlx::query( + "UPDATE script SET auto_kind = 'lib', + kind = CASE WHEN hash = 5003 THEN 'preprocessor' ELSE kind END + WHERE hash IN (5002, 5003)", + ) + .execute(&db) + .await?; + + for (query, expected) in [ + ("", vec!["u/operator/action"]), + ("&kinds=preprocessor", vec!["u/operator/prep"]), + ( + "&kinds=script,preprocessor", + vec!["u/operator/action", "u/operator/prep"], + ), + ] { + let scripts: Vec = c + .get(format!("{api}/scripts/list?path_start=u/operator/{query}")) + .send() + .await? + .error_for_status()? + .json() + .await?; + let mut paths: Vec<&str> = scripts.iter().filter_map(|s| s["path"].as_str()).collect(); + paths.sort(); + assert_eq!(paths, expected, "scripts listed for `{query}`"); + } + Ok(()) +} 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-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 f8159c22eb..e063874533 100644 --- a/backend/windmill-api-scripts/src/scripts.rs +++ b/backend/windmill-api-scripts/src/scripts.rs @@ -194,7 +194,7 @@ async fn list_scripts( Query(pagination): Query, Query(lq): Query, ) -> JsonResult> { - // A role that cannot write code lists only what it can run: no libraries, no drafts. + // A role that cannot write code lists only what it can run or compose: no libraries, no drafts. let cannot_code = !windmill_common::roles::caller_capabilities(&db, &w_id, &authed) .await? .code; @@ -259,16 +259,19 @@ async fn list_scripts( .limit(per_page) .clone(); - let lowercased_kinds: Option> = lq + let mut lowercased_kinds: Option> = lq .kinds .map(|x| x.split(",").map(&str::to_lowercase).collect()); - if (!lq.include_without_main.unwrap_or(false) + if cannot_code { + lowercased_kinds.get_or_insert_with(|| vec!["script".to_string()]); + // A preprocessor has no main, so it is a 'lib' that a composed flow can still use. + sqlb.and_where("(o.auto_kind IS NULL OR o.auto_kind <> 'lib' OR o.kind = 'preprocessor')"); + } else if !lq.include_without_main.unwrap_or(false) && lowercased_kinds .as_ref() .map(|x| !x.contains(&"preprocessor".to_string())) - .unwrap_or(true)) - || cannot_code + .unwrap_or(true) { // only include scripts that have a runnable entrypoint. Use a // deny-list: anything that isn't a 'lib' (library script without @@ -325,9 +328,7 @@ async fn list_scripts( ); } } - if cannot_code { - sqlb.and_where_eq("kind", quote("script")); - } else if let Some(lowercased_kinds) = lowercased_kinds { + if let Some(lowercased_kinds) = lowercased_kinds { let safe_kinds = lowercased_kinds .into_iter() .map(sql_builder::quote) 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..0abbb904db 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 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..d6e6672080 100644 --- a/backend/windmill-api-settings/src/lib.rs +++ b/backend/windmill-api-settings/src/lib.rs @@ -878,8 +878,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) @@ -1348,12 +1358,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 +1382,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 @@ -1387,9 +1408,13 @@ async fn set_instance_config( .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 @@ -1495,6 +1520,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 +1565,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 +1602,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 +1610,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)) diff --git a/backend/windmill-api-users/src/users.rs b/backend/windmill-api-users/src/users.rs index cda45ea055..1c80a8ec28 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::ClientIp; use windmill_api_auth::ApiAuthed; @@ -1278,6 +1279,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) @@ -2846,6 +2855,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, @@ -2866,7 +2879,7 @@ async fn set_login_type( #[allow(unreachable_code, unused_variables)] async fn login( - headers: axum::http::HeaderMap, + ClientIp(client_ip): ClientIp, cookies: Cookies, Extension(db): Extension, Extension(argon2): Extension>>, @@ -2889,7 +2902,7 @@ async fn login( )); } - windmill_common::login_rate_limit::check_and_increment_login_attempt(&headers, &email)?; + windmill_common::login_rate_limit::check_and_increment_login_attempt(client_ip, &email)?; let mut tx = db.begin().await?; let audit_author = AuditAuthor { @@ -3861,7 +3874,7 @@ struct LoginLinkQuery { } async fn consume_login_link( - headers: axum::http::HeaderMap, + ClientIp(client_ip): ClientIp, cookies: Cookies, Extension(db): Extension, Path(token): Path, @@ -3879,7 +3892,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], )?; diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index 27466bf9e7..d0e94ff02d 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)) @@ -12055,6 +12056,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 +12269,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 +12858,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 diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 5db550b129..4c7e907136 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.885.0 title: Windmill API contact: @@ -1903,6 +1903,7 @@ paths: - setting parameters: - $ref: "#/components/parameters/Key" + - $ref: "#/components/parameters/DangerouslyRevealSecrets" responses: "200": description: status @@ -2717,6 +2718,8 @@ paths: operationId: listGlobalSettings tags: - setting + parameters: + - $ref: "#/components/parameters/DangerouslyRevealSecrets" responses: "200": description: list of settings @@ -2760,6 +2763,8 @@ paths: operationId: getInstanceConfig tags: - setting + parameters: + - $ref: "#/components/parameters/DangerouslyRevealSecrets" responses: "200": description: full instance configuration @@ -8312,6 +8317,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 @@ -13174,6 +13210,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 +13408,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 +13430,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 @@ -20297,6 +20481,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 +20496,11 @@ paths: type: integer approver: type: string + approved_at: + type: string + format: date-time + approved: + type: boolean view_token: type: string description: >- @@ -20563,6 +20755,11 @@ paths: type: integer approver: type: string + approved_at: + type: string + format: date-time + approved: + type: boolean required: - resume_id - approver @@ -27816,6 +28013,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 @@ -29718,6 +29947,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 @@ -33709,9 +33947,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: @@ -34256,6 +34519,12 @@ 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 (loopback by default, plus the private ranges on Windmill Cloud), so behind a reverse proxy this is the proxy's address until it is listed. Absent on entries no request stands behind. + user_agent: + type: string + description: User-Agent header of the request. required: - workspace_id - id @@ -34443,9 +34712,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 @@ -41465,6 +41736,7 @@ components: - RestrictPublicRunSharing - RestrictGuestAppDeployment - RequireIsolatedForks + - RequireSso RuleBypasserGroups: type: array description: Groups that can bypass this ruleset 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..45136f5b95 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- 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\"},\"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\"},\"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,7 +317,7 @@ "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", + "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## 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/capture.rs b/backend/windmill-api/src/capture.rs index 14b46a6085..c2a5dc29e5 100644 --- a/backend/windmill-api/src/capture.rs +++ b/backend/windmill-api/src/capture.rs @@ -578,6 +578,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?; diff --git a/backend/windmill-api/src/concurrency_groups.rs b/backend/windmill-api/src/concurrency_groups.rs index aab73c81d9..3e0a136b30 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,6 +34,44 @@ 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 require_concurrency_key_read( + token: &str, + 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 + // that does not exist, so both answer with the same 404. + let job = sqlx::query!( + "SELECT workspace_id, created_by FROM v2_job WHERE id = $1", + job_id + ) + .fetch_optional(db) + .await? + .ok_or_else(not_found)?; + + let authed_in_workspace = cache + .get_authed(Some(job.workspace_id.clone()), token) + .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, + &authed_in_workspace, + &job.workspace_id, + &job_id, + &job.created_by, + view_token, + ) + .await +} + async fn get_concurrency_key( _authed: ApiAuthed, Tokened { token }: Tokened, @@ -40,37 +81,42 @@ async fn get_concurrency_key( OptViewToken(view_token): OptViewToken, Path(job_id): Path<Uuid>, ) -> JsonResult<Option<String>> { - 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 - // that does not exist, so both answer with the same 404. - let job = sqlx::query!( - "SELECT workspace_id, created_by FROM v2_job WHERE id = $1", - job_id - ) - .fetch_optional(&db) - .await? - .ok_or_else(not_found)?; - - let authed_in_workspace = cache - .get_authed(Some(job.workspace_id.clone()), &token) - .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, - &authed_in_workspace, - &job.workspace_id, - &job_id, - &job.created_by, - view_token.as_deref(), - ) - .await?; - + require_concurrency_key_read(&token, &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, + 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, &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/jobs.rs b/backend/windmill-api/src/jobs.rs index fd13006181..50f7463bda 100644 --- a/backend/windmill-api/src/jobs.rs +++ b/backend/windmill-api/src/jobs.rs @@ -409,6 +409,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()), @@ -5348,6 +5353,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 +5448,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 +5540,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 +5621,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 +5632,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 +5658,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 +5694,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 +5746,7 @@ async fn get_approval_info( skin, step_summary, flow_summary: row.flow_summary, + required_events, approvers, view_token, })) @@ -5744,11 +5766,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 +6249,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 +6267,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 +6330,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 +6383,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 { @@ -6594,6 +6978,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 { @@ -13625,3 +14011,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..26535b211f 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -323,6 +323,25 @@ async fn set_request_client( windmill_common::trigger_history::scope_client(client, 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 = (); @@ -1292,6 +1311,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 +1329,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, diff --git a/backend/windmill-api/src/live_migrations.rs b/backend/windmill-api/src/live_migrations.rs index a620807902..866eed1fab 100644 --- a/backend/windmill-api/src/live_migrations.rs +++ b/backend/windmill-api/src/live_migrations.rs @@ -367,8 +367,11 @@ 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 \ + 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/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-audit/src/lib.rs b/backend/windmill-audit/src/lib.rs index 89b5de067a..4371705f5f 100644 --- a/backend/windmill-audit/src/lib.rs +++ b/backend/windmill-audit/src/lib.rs @@ -26,6 +26,10 @@ 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>, } #[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/client_ip.rs b/backend/windmill-common/src/client_ip.rs new file mode 100644 index 0000000000..13fd40460d --- /dev/null +++ b/backend/windmill-common/src/client_ip.rs @@ -0,0 +1,317 @@ +//! The address a request comes from, for decisions that must not be spoofable (per-IP rate +//! limits, token IP allowlists). +//! +//! Forwarding headers are believed only when the TCP peer is in `TRUSTED_PROXIES`. 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. + +use std::net::{IpAddr, SocketAddr}; +use std::sync::LazyLock; + +use axum::extract::{ConnectInfo, FromRequestParts}; +use axum::http::{request::Parts, HeaderMap, HeaderName}; +use ipnet::IpNet; + +/// Loopback, private and link-local networks: where a reverse proxy in front of Windmill +/// usually connects from. Anything else in front (a CDN, a public load balancer) must be listed +/// in `TRUSTED_PROXIES`, or its own address is taken as the client's. Job code on the same +/// network is trusted too, so a deployment where jobs can reach the server directly should list +/// its proxy's exact address instead. +const DEFAULT_TRUSTED_PROXIES: &[&str] = &[ + "127.0.0.0/8", + "::1/128", + "10.0.0.0/8", + "172.16.0.0/12", + "192.168.0.0/16", + "169.254.0.0/16", + "fc00::/7", + "fe80::/10", +]; + +pub struct ClientIpConfig { + pub trusted: Vec<IpNet>, + pub header: Option<HeaderName>, +} + +/// `TRUSTED_PROXIES`: comma-separated IPs or CIDRs; set but empty, or `none`, trusts no proxy. +/// `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`. +pub static CLIENT_IP_CONFIG: LazyLock<ClientIpConfig> = LazyLock::new(|| { + let trusted = match std::env::var("TRUSTED_PROXIES") { + Ok(v) => parse_trusted_proxies(&v), + Err(_) => parse_trusted_proxies(&DEFAULT_TRUSTED_PROXIES.join(",")), + }; + let header = std::env::var("CLIENT_IP_HEADER") + .ok() + .filter(|v| !v.trim().is_empty()) + .and_then(|v| match HeaderName::try_from(v.trim()) { + Ok(h) => Some(h), + Err(_) => { + tracing::error!("CLIENT_IP_HEADER: {v:?} is not a header name, ignoring it"); + None + } + }); + ClientIpConfig { trusted, header } +}); + +fn parse_trusted_proxies(v: &str) -> Vec<IpNet> { + if v.trim().eq_ignore_ascii_case("none") { + return vec![]; + } + v.split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .filter_map(|s| { + let parsed = s + .parse::<IpNet>() + .ok() + .or_else(|| s.parse::<IpAddr>().ok().map(IpNet::from)); + if parsed.is_none() { + tracing::error!("TRUSTED_PROXIES: ignoring invalid entry {s:?}"); + } + parsed + }) + .collect() +} + +/// The client address of a request: `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))) + } +} + +pub fn client_ip_of_parts(parts: &Parts) -> Option<IpAddr> { + let peer = parts + .extensions + .get::<ConnectInfo<SocketAddr>>() + .map(|c| c.0.ip())?; + Some(resolve_client_ip(peer, &parts.headers, &CLIENT_IP_CONFIG)) +} + +/// 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, + } +} + +fn is_trusted(ip: IpAddr, trusted: &[IpNet]) -> bool { + trusted.iter().any(|n| n.contains(&ip)) +} + +/// 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) +} + +pub fn resolve_client_ip(peer: IpAddr, headers: &HeaderMap, cfg: &ClientIpConfig) -> IpAddr { + let peer = canonical(peer); + if !is_trusted(peer, &cfg.trusted) { + 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, + }; + } + // 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 !is_trusted(ip, &cfg.trusted) { + return ip; + } + } + client +} + +#[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 { + ClientIpConfig { + trusted: parse_trusted_proxies(trusted), + header: header.map(HeaderName::from_static), + } + } + + fn defaults() -> ClientIpConfig { + cfg(&DEFAULT_TRUSTED_PROXIES.join(","), None) + } + + #[test] + fn untrusted_peer_ignores_forwarding_headers() { + let h = headers(&[("x-forwarded-for", b"10.0.0.9")]); + assert_eq!( + resolve_client_ip(ip("1.2.3.4"), &h, &defaults()), + 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 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 mapped_v4_is_v4_and_none_trusts_no_proxy() { + 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("127.0.0.1"), &h, &cfg("none", None)), + ip("127.0.0.1") + ); + assert_eq!( + resolve_client_ip(ip("127.0.0.1"), &h, &cfg("", None)), + ip("127.0.0.1") + ); + } +} diff --git a/backend/windmill-common/src/global_settings.rs b/backend/windmill-common/src/global_settings.rs index e87dd17a76..4792d02e63 100644 --- a/backend/windmill-common/src/global_settings.rs +++ b/backend/windmill-common/src/global_settings.rs @@ -924,6 +924,7 @@ pub const ENV_SETTINGS: &[&str] = &[ "WORKER_GROUP", "SAML_METADATA", "INSTANCE_IS_DEV", + "TRUSTED_PROXIES", "OTEL_METRICS", "OTEL_TRACING", "OTEL_LOGS", @@ -932,6 +933,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..16e8f97a07 100644 --- a/backend/windmill-common/src/instance_config.rs +++ b/backend/windmill-common/src/instance_config.rs @@ -649,6 +649,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")] @@ -1200,6 +1215,11 @@ const SENSITIVE_SETTINGS: &[&str] = &[ "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 +1244,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 +1301,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 +1632,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, @@ -1786,20 +1909,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 +1939,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 +2968,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 +3135,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!({ diff --git a/backend/windmill-common/src/lib.rs b/backend/windmill-common/src/lib.rs index 822b0fda31..84a509a5df 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"))] @@ -98,6 +99,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 +484,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); @@ -3467,3 +3473,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/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/request_origin.rs b/backend/windmill-common/src/request_origin.rs new file mode 100644 index 0000000000..7b8b41c49d --- /dev/null +++ b/backend/windmill-common/src/request_origin.rs @@ -0,0 +1,192 @@ +//! Where the request being served came from: the client's IP address and user agent, as +//! recorded on the audit entries it writes. + +use std::net::IpAddr; +use std::sync::{Arc, LazyLock}; + +use http::HeaderMap; +use ipnet::IpNet; + +use crate::utils::truncate_chars; +use crate::worker::CLOUD_HOSTED; + +const USER_AGENT_MAX_CHARS: usize = 512; + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RequestOrigin { + pub client_ip: Option<IpAddr>, + pub user_agent: 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() +} + +/// The proxies whose forwarding headers are believed. `TRUSTED_PROXIES` (comma-separated +/// addresses or CIDRs, empty for none) replaces the default: loopback, plus the private +/// ranges on cloud, where every request arrives through our own load balancer. Private +/// ranges are not trusted by default elsewhere: a self-hosted instance is often reached +/// directly from a private network, and its clients could then name any address they like. +static TRUSTED_PROXIES: LazyLock<Vec<IpNet>> = + LazyLock::new(|| match std::env::var("TRUSTED_PROXIES") { + Ok(v) => parse_trusted_proxies(&v), + Err(_) => { + let mut nets = vec!["127.0.0.0/8", "::1/128"]; + if *CLOUD_HOSTED { + nets.extend(["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]); + } + nets.into_iter().filter_map(|n| n.parse().ok()).collect() + } + }); + +fn parse_trusted_proxies(v: &str) -> Vec<IpNet> { + v.split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .filter_map(|s| { + let parsed = s + .parse::<IpNet>() + .ok() + .or_else(|| s.parse::<IpAddr>().ok().map(IpNet::from)); + if parsed.is_none() { + tracing::warn!("Ignoring invalid TRUSTED_PROXIES entry: {s}"); + } + parsed + }) + .collect() +} + +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 { + Self { + client_ip: peer.map(|p| client_ip(p, headers, &TRUSTED_PROXIES)), + 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()), + } + } +} + +fn parse_hop(s: &str) -> Option<IpAddr> { + let s = s.trim(); + s.parse::<IpAddr>() + .ok() + .or_else(|| s.parse::<std::net::SocketAddr>().ok().map(|a| a.ip())) + .map(|ip| ip.to_canonical()) +} + +/// The first address that is not a trusted proxy, walking `X-Forwarded-For` back from the +/// peer: each trusted hop vouches for the address before it, an untrusted one for nothing, +/// so entries left of it are whatever the client wrote. `X-Real-IP` is read only when there +/// is no `X-Forwarded-For`. +fn client_ip(peer: IpAddr, headers: &HeaderMap, trusted: &[IpNet]) -> IpAddr { + let is_trusted = |ip: &IpAddr| trusted.iter().any(|n| n.contains(ip)); + let mut current = peer.to_canonical(); + if !is_trusted(¤t) { + return current; + } + // Bytes that are not UTF-8 are kept as entries that fail to parse, so they stop the walk + // rather than vanish and let the client's own entries, or X-Real-IP, stand in. + let values: Vec<String> = headers + .get_all("x-forwarded-for") + .iter() + .map(|v| String::from_utf8_lossy(v.as_bytes()).into_owned()) + .collect(); + let hops: Vec<&str> = values.iter().flat_map(|v| v.split(',')).collect(); + if values.is_empty() { + if let Some(ip) = headers + .get("x-real-ip") + .and_then(|v| v.to_str().ok()) + .and_then(parse_hop) + { + return ip; + } + return current; + } + for hop in hops.iter().rev() { + if !is_trusted(¤t) { + break; + } + match parse_hop(hop) { + Some(ip) => current = ip, + None => break, + } + } + current +} + +#[cfg(test)] +mod tests { + use super::*; + + fn headers(pairs: &[(&'static str, &str)]) -> HeaderMap { + let mut h = HeaderMap::new(); + for (k, v) in pairs { + h.append(*k, v.parse().unwrap()); + } + h + } + + fn ip(s: &str) -> IpAddr { + s.parse().unwrap() + } + + #[test] + fn forwarded_addresses_are_believed_only_through_trusted_hops() { + let trusted = parse_trusted_proxies("10.0.0.0/8, 127.0.0.1"); + let xff = headers(&[("x-forwarded-for", "6.6.6.6, 1.2.3.4, 10.0.0.2")]); + + // An untrusted peer's headers say nothing. + assert_eq!(client_ip(ip("8.8.8.8"), &xff, &trusted), ip("8.8.8.8")); + // Trusted peer and trusted hop: the client is the first untrusted address, and the + // entry the client itself wrote left of it is ignored. + assert_eq!(client_ip(ip("10.0.0.1"), &xff, &trusted), ip("1.2.3.4")); + // Every hop trusted: the leftmost one. + let all_trusted = headers(&[("x-forwarded-for", "10.1.1.1, 10.0.0.2")]); + assert_eq!( + client_ip(ip("127.0.0.1"), &all_trusted, &trusted), + ip("10.1.1.1") + ); + // An unparseable hop stops the walk at the last address vouched for. + let garbage = headers(&[("x-forwarded-for", "1.2.3.4, unknown")]); + assert_eq!( + client_ip(ip("10.0.0.1"), &garbage, &trusted), + ip("10.0.0.1") + ); + // A hop that is not UTF-8 stops the walk too, and does not let X-Real-IP in. + let mut binary = headers(&[("x-real-ip", "5.5.5.5")]); + binary.append( + "x-forwarded-for", + http::HeaderValue::from_bytes(b"\x80, 1.2.3.4").unwrap(), + ); + assert_eq!(client_ip(ip("10.0.0.1"), &binary, &trusted), ip("1.2.3.4")); + let mut binary_last = headers(&[("x-real-ip", "5.5.5.5")]); + binary_last.append( + "x-forwarded-for", + http::HeaderValue::from_bytes(b"1.2.3.4, \x80").unwrap(), + ); + assert_eq!(client_ip(ip("10.0.0.1"), &binary_last, &trusted), ip("10.0.0.1")); + // X-Real-IP, only from a trusted peer and only without X-Forwarded-For. + let real = headers(&[("x-real-ip", "5.5.5.5")]); + assert_eq!(client_ip(ip("10.0.0.1"), &real, &trusted), ip("5.5.5.5")); + assert_eq!(client_ip(ip("8.8.8.8"), &real, &trusted), ip("8.8.8.8")); + // Nothing trusted. + assert_eq!(client_ip(ip("10.0.0.1"), &xff, &[]), ip("10.0.0.1")); + } +} 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/workspaces.rs b/backend/windmill-common/src/workspaces.rs index 35d157b2e0..60c03d72bc 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" + } } } } @@ -1555,6 +1561,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-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-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-queue/src/jobs.rs b/backend/windmill-queue/src/jobs.rs index e3d488bbea..ef9ae9b068 100644 --- a/backend/windmill-queue/src/jobs.rs +++ b/backend/windmill-queue/src/jobs.rs @@ -5619,6 +5619,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, 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/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..985c0f358a 100644 --- a/backend/windmill-types/src/flow_status.rs +++ b/backend/windmill-types/src/flow_status.rs @@ -136,6 +136,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 +217,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 +274,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 +296,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 +403,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..3d8b4b021c 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. 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/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..cfddc5aa0c 100644 --- a/backend/windmill-worker/src/worker.rs +++ b/backend/windmill-worker/src/worker.rs @@ -7072,7 +7072,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 +7617,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 +7630,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..480e27196d 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::{ @@ -3600,6 +3601,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 +4197,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 +4358,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 +4403,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( @@ -7574,6 +7585,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/benchmarks/lib.ts b/benchmarks/lib.ts index e5a34f716e..970098fe75 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.885.0"; 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..1efd90ad36 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.885.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/chat-sdk", - "version": "1.884.1", + "version": "1.885.0", "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..a8131104bf 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.885.0", "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/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/core/constants.ts b/cli/src/core/constants.ts index 217e10b177..6d4b055629 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.885.0"; 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..c9c31f3b17 100644 --- a/cli/src/guidance/skills.gen.ts +++ b/cli/src/guidance/skills.gen.ts @@ -6612,7 +6612,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"},"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"},"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 +8659,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. | @@ -9205,6 +9205,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 +9228,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-...) diff --git a/cli/src/utils/metadata.ts b/cli/src/utils/metadata.ts index 711d510f96..394ea607e7 100644 --- a/cli/src/utils/metadata.ts +++ b/cli/src/utils/metadata.ts @@ -229,12 +229,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 +245,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 +311,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 +353,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 +1097,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 +1144,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/test/unified_generate_metadata.test.ts b/cli/test/unified_generate_metadata.test.ts index bb73e54b37..fceb8aec94 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).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/docs/auth-surface.md b/docs/auth-surface.md index 90157c4a31..600bfc1ad9 100644 --- a/docs/auth-surface.md +++ b/docs/auth-surface.md @@ -164,6 +164,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 +232,14 @@ 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`, the `ClientIp` extractor) is the TCP + peer unless that peer is in `TRUSTED_PROXIES` (comma-separated CIDRs; unset means loopback, + private and link-local ranges; `none` trusts nothing). 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. The private-range default also trusts + job containers that can reach the server directly; such a deployment should list its proxy's + exact address. 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. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 1e666a45a5..3e15950690 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.885.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/components", - "version": "1.884.1", + "version": "1.885.0", "hasInstallScript": true, "license": "AGPL-3.0", "dependencies": { diff --git a/frontend/package.json b/frontend/package.json index 465ca8d47e..d381b2dd09 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@windmill-labs/components", - "version": "1.884.1", + "version": "1.885.0", "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", 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/components/Editor.svelte b/frontend/src/lib/components/Editor.svelte index da930c03f4..f1af18bf1c 100644 --- a/frontend/src/lib/components/Editor.svelte +++ b/frontend/src/lib/components/Editor.svelte @@ -112,10 +112,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 +170,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 +215,8 @@ loadAsync = false, key = undefined, class: clazz = undefined, - moduleId = undefined, + codeSource = undefined, + codeSourceLang = undefined, enablePreprocessorSnippet = false, rawAppRunnableKey = undefined, preparedAssetsSqlQueries, @@ -282,6 +288,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 +420,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 +1042,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 +1676,6 @@ editor?.addCommand(KeyMod.CtrlCmd | KeyCode.DownArrow, function () { if (aiChatManager.pendingNewCode) { aiChatManager.scriptEditorApplyCode?.(aiChatManager.pendingNewCode) - if (showInlineAIChat) { - closeAIInlineWidget() - } } }) @@ -1649,35 +1704,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 +1932,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) { @@ -2008,9 +2024,6 @@ rejectCodeChanges() } else if ((e.ctrlKey || e.metaKey) && e.key === 'ArrowDown' && aiChatManager.pendingNewCode) { acceptCodeChanges() - if (showInlineAIChat) { - closeAIInlineWidget() - } } } $effect(() => { @@ -2250,14 +2263,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/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/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/InstanceSetting.svelte b/frontend/src/lib/components/InstanceSetting.svelte index 32c97f6623..48323cab2a 100644 --- a/frontend/src/lib/components/InstanceSetting.svelte +++ b/frontend/src/lib/components/InstanceSetting.svelte @@ -23,6 +23,7 @@ import RetentionPeriodOverrides from './instanceSettings/RetentionPeriodOverrides.svelte' import AgentWorkloadIdentityIssuers from './instanceSettings/AgentWorkloadIdentityIssuers.svelte' import McpExternalIdp from './instanceSettings/McpExternalIdp.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 +129,8 @@ async function reloadLicenseKey() { $values['license_key'] = await SettingService.getGlobal({ - key: 'license_key' + key: 'license_key', + dangerouslyRevealSecrets: true }) } @@ -724,6 +726,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..961452b4c0 100644 --- a/frontend/src/lib/components/InstanceSettings.svelte +++ b/frontend/src/lib/components/InstanceSettings.svelte @@ -135,7 +135,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'] ?? {} 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/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/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/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/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/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/auditLogs/AuditLogDetails.svelte b/frontend/src/lib/components/auditLogs/AuditLogDetails.svelte index 1289deb222..edab31d0f4 100644 --- a/frontend/src/lib/components/auditLogs/AuditLogDetails.svelte +++ b/frontend/src/lib/components/auditLogs/AuditLogDetails.svelte @@ -62,6 +62,18 @@ </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.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/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/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 6055705c8a..a86d8e30e4 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts @@ -40,17 +40,14 @@ import { createJobUpdateReader, deriveChatJobStatus, pendingToolImagesMessage, + type ToolImage, trimJob } from './shared' 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' @@ -126,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 { @@ -470,7 +469,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 @@ -536,7 +535,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) @@ -795,7 +793,7 @@ export class AIChatManager implements ChatViewHost { /** Images buffered by tools (e.g. take_screenshot) during the current tool batch, * keyed by toolId. Drained by appendPendingToolImages into a follow-up user message * after the batch. Cleared at each turn start so an aborted batch can't leak. */ - private pendingToolImages = new Map<string, AttachedImage[]>() + private pendingToolImages = new Map<string, ToolImage[]>() /** Model of the most recent loop iteration, recorded via onBeforeIteration. * The selector stays switchable mid-flight, so when a request fails neither * the send-time nor the currently-selected model necessarily names the one @@ -2880,7 +2878,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 @@ -2912,7 +2911,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))) { @@ -2923,33 +2922,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. * @@ -2975,7 +2964,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 @@ -2983,6 +2974,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()) { @@ -2998,27 +2993,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 } @@ -3592,29 +3591,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 @@ -3911,92 +3909,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 @@ -4114,13 +4026,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({}) } @@ -4174,8 +4080,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) @@ -4211,7 +4116,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( @@ -4247,12 +4153,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). */ @@ -4326,6 +4226,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)) { @@ -4395,17 +4297,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 } @@ -4433,7 +4334,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( @@ -4458,7 +4359,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) } @@ -4516,16 +4422,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: ${ @@ -4583,14 +4484,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 } @@ -4691,27 +4589,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) @@ -4792,7 +4679,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 @@ -4871,7 +4758,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. @@ -5106,27 +4993,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 @@ -5328,15 +5204,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 @@ -5442,16 +5309,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 @@ -5461,16 +5327,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 089afb5290..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') @@ -2627,8 +2647,8 @@ describe('AIChatManager queued messages', () => { { role: 'tool' as const, tool_call_id: 'shot', content: 'Screenshot attached below' } ) config.callbacks.attachToolImage('shot', { - dataUrl: 'data:image/png;base64,iVBORw0KGgo=', - name: 'shot.png' + image: { dataUrl: 'data:image/png;base64,iVBORw0KGgo=', name: 'shot.png' }, + caption: 'Screenshot(s) of the app preview:' }) leavePage.forEach((fn) => fn()) return { @@ -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/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/ToolExecutionDisplay.svelte b/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte index 684c9c4dee..63ef5d1ef8 100644 --- a/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte @@ -403,7 +403,7 @@ <div class="my-1"> <ExpandableImage src={message.imageUrl} - alt="App preview screenshot" + alt="Image returned by the tool" class="max-h-48 max-w-full rounded border border-border-light" /> </div> 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 4beb4a7e03..f23a2ab1d8 100644 --- a/frontend/src/lib/components/copilot/chat/chatViewHost.ts +++ b/frontend/src/lib/components/copilot/chat/chatViewHost.ts @@ -26,13 +26,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' } /** 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/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..48d1e62c8d 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.882.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"},"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"},"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..55f50bdb1b 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"), "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() }).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) => @@ -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 ea5310231c..c618e8b9b4 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -126,7 +126,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' @@ -4830,7 +4837,10 @@ export const globalTools: SessionTool<{}>[] = [ // buffered here and flushed as a follow-up user image message once the tool batch // completes (see appendPendingToolImages). const image = await normalizeImageDataUrl(result.dataUrl) - ctx.toolCallbacks.attachToolImage?.(ctx.toolId, image) + ctx.toolCallbacks.attachToolImage?.(ctx.toolId, { + image, + caption: 'Screenshot(s) of the app preview:' + }) // The card shows the same copy the model gets; sharing the exact data URL // lets the history's blob store persist one copy for both. ctx.toolCallbacks.setToolStatus(ctx.toolId, { @@ -7874,6 +7884,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[] = [], @@ -7944,6 +7970,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 30a4403746..8a95f6032a 100644 --- a/frontend/src/lib/components/copilot/chat/global/mcpTools.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/mcpTools.test.ts @@ -22,12 +22,20 @@ vi.mock('$lib/gen', () => ({ } })) +vi.mock('$lib/aiStore', () => ({ tryGetCurrentModel: () => undefined })) + vi.mock('$lib/stores', () => ({ // Read at call time, so a test can switch accounts the way a logout does. userStore: { subscribe: (run: (v: unknown) => void) => (run({ ...session }), () => {}) } })) -import { clearMcpToolsCache, createMcpTools, loadMcpServers, type McpServer } from './mcpTools' +import { + clearMcpToolsCache, + createMcpTools, + loadMcpServers, + splitMcpResult, + type McpServer +} from './mcpTools' import { setMcpEnabled } from '$lib/components/mcp/enabledServers' const SERVERS: McpServer[] = [{ path: 'u/hugo/github_mcp' }] @@ -222,6 +230,32 @@ describe('call results', () => { expect(result.error).toBe('issue not found') }) + it('takes image blocks out of the text, and drops an oversized one whole', () => { + const small = 'iVBORw0KGgo=' + const huge = 'A'.repeat(11_000_000) + const { data, images, omitted } = splitMcpResult({ + content: [ + { type: 'text', text: 'Viewport of Blender' }, + { type: 'image', mimeType: 'image/png', data: small }, + { type: 'image', mimeType: 'image/png', data: huge } + ] + }) + expect(data).toBe('Viewport of Blender') + expect(images).toEqual([{ index: 0, mimeType: 'image/png', data: small }]) + expect(omitted).toEqual(['image 2 (image/png): larger than 8 MB']) + }) + + it('keeps structured content when images are taken out', () => { + const { data } = splitMcpResult({ + content: [ + { type: 'text', text: 'Rendered' }, + { type: 'image', mimeType: 'image/png', data: 'iVBORw0KGgo=' } + ], + structuredContent: { object_id: 'cube-17' } + }) + expect(data).toEqual({ object_id: 'cube-17' }) + }) + it('flattens text content on success', async () => { callMcpToolMock.mockResolvedValue({ content: [{ type: 'text', text: '{"number":42}' }] }) const result = await run('call_mcp_read_tool', { diff --git a/frontend/src/lib/components/copilot/chat/global/mcpTools.ts b/frontend/src/lib/components/copilot/chat/global/mcpTools.ts index b91df4c769..8917c6e23f 100644 --- a/frontend/src/lib/components/copilot/chat/global/mcpTools.ts +++ b/frontend/src/lib/components/copilot/chat/global/mcpTools.ts @@ -4,6 +4,10 @@ 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 { MAX_ATTACHED_IMAGES, normalizeImageDataUrl, type AttachedImage } from '../imageUtils' +import { modelSupportsVision } from '../../modelConfig' +import { tryGetCurrentModel } from '$lib/aiStore' +import type { GlobalToolHelpers } from './core' /** * Access to the MCP servers the user has connected (resources of type `mcp`) @@ -20,6 +24,9 @@ export type McpServer = { path: string; editedAt?: string } const MAX_SEARCH_RESULTS = 10 const MAX_DESCRIPTION_CHARS = 1_000 const MAX_RESULT_CHARS = 20_000 +// Checked on the server's raw image, before it is decoded and downscaled: decoding +// allocates the full bitmap, so the cap has to bite first. +const MAX_IMAGE_BYTES = 8_000_000 // A server writes its own error text, and every enabled server can contribute // one, so search results are capped the same way call results are. const MAX_SERVER_ERROR_CHARS = 500 @@ -185,17 +192,72 @@ async function resolveTool( return { server, tool } } -/** Flatten the MCP content blocks into the text the model can act on. */ -function extractResultData(result: unknown): unknown { +/** `index` counts the result's image blocks, so a note names the one the server sent. */ +export type McpImage = { index: number; mimeType: string; data: string } + +/** Decoded bytes of base64 text, without decoding it. */ +function base64Size(b64: string): number { + const padding = b64.endsWith('==') ? 2 : b64.endsWith('=') ? 1 : 0 + return Math.max(0, Math.floor((b64.length * 3) / 4) - padding) +} + +function describeImage(index: number, mimeType: string): string { + return `image ${index + 1} (${truncate(mimeType, 40)})` +} + +/** + * Split an MCP result into the data the model reads as text and the image blocks it + * is shown as images. Images never go into the text: base64 cut at the text cap is + * unreadable, so an image over the limits is dropped whole and named in `omitted`. + */ +export function splitMcpResult(result: unknown): { + data: unknown + images: McpImage[] + omitted: string[] +} { const content = (result as { content?: unknown })?.content - if (Array.isArray(content)) { - const texts = content - .filter((c) => (c as { type?: string })?.type === 'text') - .map((c) => (c as { text?: string }).text ?? '') - if (texts.length === content.length) return texts.join('\n') + const images: McpImage[] = [] + const omitted: string[] = [] + if (!Array.isArray(content)) { + const structured = (result as { structuredContent?: unknown })?.structuredContent + return { data: structured ?? content ?? result, images, omitted } } + let imageIndex = 0 + const rest = content.filter((c) => { + const block = c as { type?: string; data?: unknown; mimeType?: unknown } + if (block?.type !== 'image') return true + const index = imageIndex++ + const mimeType = typeof block.mimeType === 'string' ? block.mimeType : 'unknown type' + if (typeof block.data !== 'string' || !mimeType.startsWith('image/')) { + omitted.push(`${describeImage(index, mimeType)}: not a base64 image`) + } else if (base64Size(block.data) > MAX_IMAGE_BYTES) { + omitted.push( + `${describeImage(index, mimeType)}: larger than ${MAX_IMAGE_BYTES / 1_000_000} MB` + ) + } else if (images.length >= MAX_ATTACHED_IMAGES) { + omitted.push(`${describeImage(index, mimeType)}: over ${MAX_ATTACHED_IMAGES} images`) + } else { + images.push({ index, mimeType, data: block.data }) + } + return false + }) + const texts = rest + .filter((c) => (c as { type?: string })?.type === 'text') + .map((c) => (c as { text?: string }).text ?? '') const structured = (result as { structuredContent?: unknown })?.structuredContent - return structured ?? content ?? result + // A result that mixed in images was never read as text alone: its structured + // content is what carried the fields, so taking the images out must not drop it. + const textOnly = rest.length === content.length || structured === undefined + if (texts.length === rest.length && textOnly) return { data: texts.join('\n'), images, omitted } + return { data: structured ?? rest, images, omitted } +} + +/** What the model is told about the images a call returned, or undefined for none. */ +function imagesNote(attached: number, omitted: string[]): string | undefined { + const parts: string[] = [] + if (attached > 0) parts.push(`${attached} image(s) attached in the following message.`) + if (omitted.length > 0) parts.push(`Not shown: ${omitted.join('; ')}.`) + return parts.length > 0 ? truncate(parts.join(' '), MAX_SERVER_ERROR_CHARS) : undefined } async function executeTool( @@ -203,8 +265,9 @@ async function executeTool( server: McpServer, tool: McpToolDef, args: Record<string, unknown>, - skippedConfirmation: boolean -): Promise<string> { + skippedConfirmation: boolean, + canSeeImages: boolean +): Promise<{ result: string; images: AttachedImage[] }> { let raw: unknown try { raw = await ResourceService.callMcpTool({ @@ -228,7 +291,7 @@ async function executeTool( if (skippedConfirmation && status === 400 && /read-only/i.test(error)) { forgetServerTools(workspace, server.path) } - return bounded({ + const result = bounded({ success: false, ...(status ? { status } : {}), error, @@ -236,19 +299,36 @@ async function executeTool( // can self-correct on the next call without a separate schema tool. ...(status >= 400 && status < 500 ? { schema: tool.inputSchema } : {}) }) + return { result, images: [] } } - const data = extractResultData(raw) + const { data, images: rawImages, omitted } = splitMcpResult(raw) // A tool that ran but reported failure comes back as a success with isError set. if ((raw as { isError?: boolean })?.isError) { - return bounded({ + const result = bounded({ success: false, error: typeof data === 'string' ? data : JSON.stringify(data), schema: tool.inputSchema }) + return { result, images: [] } } - return bounded({ success: true, data }) + const images: AttachedImage[] = [] + for (const image of rawImages) { + const name = describeImage(image.index, image.mimeType) + // A text-only model would reject the follow-up image message and fail the turn. + if (!canSeeImages) { + omitted.push(`${name}: the current model cannot read images`) + continue + } + try { + images.push(await normalizeImageDataUrl(`data:${image.mimeType};base64,${image.data}`)) + } catch { + omitted.push(`${name}: could not be decoded`) + } + } + const note = imagesNote(images.length, omitted) + return { result: bounded({ success: true, data, ...(note ? { images: note } : {}) }), images } } /** @@ -260,6 +340,8 @@ function bounded(payload: { success: boolean data?: unknown error?: string + /** Already bounded; kept through truncation, since it says what the next message holds. */ + images?: string [k: string]: unknown }) { const full = JSON.stringify(payload) @@ -276,6 +358,7 @@ function bounded(payload: { success: payload.success, truncated: true, [payload.success ? 'data' : 'error']: text.slice(0, take), + ...(payload.images ? { images: payload.images } : {}), note: `Truncated to fit ${MAX_RESULT_CHARS} characters. Use filter or pagination parameters to narrow it.` }) take = Math.floor(take / 2) @@ -371,7 +454,7 @@ function createCallTool(servers: McpServer[], mode: 'read' | 'write'): SessionTo confirmAction: 'run', confirmationMessage: (args: any) => `Call ${args?.tool ?? ''} on ${args?.server ?? ''}` }), - fn: async ({ args, workspace, toolId, toolCallbacks }) => { + fn: async ({ args, workspace, toolId, toolCallbacks, helpers }) => { const parsed = callMcpToolSchema.parse(args) // Marks the row with the provider it reaches. Recorded before the listing is // awaited, so an unreachable server still marks its own failure row, and taken @@ -401,17 +484,25 @@ function createCallTool(servers: McpServer[], mode: 'read' | 'write'): SessionTo return bounded({ success: false, error }) } toolCallbacks.setToolStatus(toolId, { content: `Calling ${parsed.tool}...` }) - const result = await executeTool( + // Re-read per call: the session's model can change between turns. + const sessionAi = (helpers as GlobalToolHelpers | undefined)?.sessionAi + const model = sessionAi ? sessionAi().model : tryGetCurrentModel() + const { result, images } = await executeTool( workspace, resolved.server, resolved.tool, parsed.arguments ?? {}, - isRead + isRead, + !model || modelSupportsVision(model.provider, model.model) ) + const caption = `Image(s) returned by ${parsed.tool} on ${resolved.server.path}:` + for (const image of images) toolCallbacks.attachToolImage?.(toolId, { image, caption }) const ok = JSON.parse(result).success === true toolCallbacks.setToolStatus(toolId, { content: ok ? `Called ${parsed.tool}` : `Call to ${parsed.tool} failed`, result, + // The card has room for one image; the model gets all of them. + ...(images.length > 0 ? { imageUrl: images[0].dataUrl } : {}), ...(ok ? {} : { error: `Call to ${parsed.tool} failed` }) }) return result 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.test.ts b/frontend/src/lib/components/copilot/chat/shared.test.ts index f4884a471d..8c512eb42c 100644 --- a/frontend/src/lib/components/copilot/chat/shared.test.ts +++ b/frontend/src/lib/components/copilot/chat/shared.test.ts @@ -1910,7 +1910,12 @@ describe('appendPendingToolImages', () => { // same screenshots again would duplicate them in history. it('appends one user message to both arrays and drains the buffer once', async () => { const { appendPendingToolImages } = await import('./shared') - let pending = [{ dataUrl: 'data:image/png;base64,SHOT', mediaType: 'image/png' as const }] + let pending = [ + { + image: { dataUrl: 'data:image/png;base64,SHOT', mediaType: 'image/png' as const }, + caption: 'Screenshot(s) of the app preview:' + } + ] const toolCallbacks = { setToolStatus: vi.fn(), takePendingToolImages: () => { diff --git a/frontend/src/lib/components/copilot/chat/shared.ts b/frontend/src/lib/components/copilot/chat/shared.ts index 53b56141e5..b23ac325f5 100644 --- a/frontend/src/lib/components/copilot/chat/shared.ts +++ b/frontend/src/lib/components/copilot/chat/shared.ts @@ -1,5 +1,6 @@ import { AI_DECISION_SCHEMA } from '../../flows/flowInfers' import type { + ChatCompletionContentPart, ChatCompletionFunctionTool, ChatCompletionMessageFunctionToolCall, ChatCompletionMessageParam @@ -38,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' @@ -354,48 +355,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 = ` @@ -427,13 +386,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') @@ -1439,20 +1392,25 @@ export async function processToolCall<T>({ * id is already answered by its tool result before this non-tool message. The image * parts ride the same `image_url` carrier that the provider converters translate. */ +/** An image a tool produced, with the line that tells the model what it shows. */ +export type ToolImage = { image: AttachedImage; caption: string } + /** The message that hands tool-produced images to the model, or undefined when * there are none. Split out so a snapshot of a turn still buffering them can * build the same message without draining the buffer the live turn still owns. */ export function pendingToolImagesMessage( - images: AttachedImage[] + images: ToolImage[] ): ChatCompletionMessageParam | undefined { if (images.length === 0) return undefined - return { - role: 'user', - content: [ - { type: 'text', text: 'Screenshot(s) of the app preview:' }, - ...images.map((img) => dataUrlToImagePart(img.dataUrl)) - ] + // One batch can mix tools, so each run of images is introduced by its own tool's caption. + const content: ChatCompletionContentPart[] = [] + let caption: string | undefined + for (const { image, caption: next } of images) { + if (next !== caption) content.push({ type: 'text', text: next }) + caption = next + content.push(dataUrlToImagePart(image.dataUrl)) } + return { role: 'user', content } } export function appendPendingToolImages( @@ -1730,9 +1688,9 @@ export interface ToolCallbacks { * appendPendingToolImages) — appending mid-batch would leave sibling tool_call ids * unanswered before a non-tool message. */ - attachToolImage?: (toolId: string, image: AttachedImage) => void + attachToolImage?: (toolId: string, image: ToolImage) => void /** Drain every image buffered this batch (insertion order), clearing the buffer. */ - takePendingToolImages?: () => AttachedImage[] + takePendingToolImages?: () => ToolImage[] /** Wired only by the global/sessions chat: delivers the folder instructions * covering the paths a tool call names, once per conversation. */ folderInstructions?: FolderInstructionsContext 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/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/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/FlowEditor.svelte b/frontend/src/lib/components/flows/FlowEditor.svelte index 39c99f38cb..21104c7551 100644 --- a/frontend/src/lib/components/flows/FlowEditor.svelte +++ b/frontend/src/lib/components/flows/FlowEditor.svelte @@ -325,6 +325,13 @@ aiChatManager.changeMode(AIMode.NAVIGATOR) } }) + + // The docked scroller outlives the selection, so without this a step opens at the scroll + // position of the one selected before it. + function scrollToTopOnSelect(node: HTMLElement) { + selectionManager.getSelectedId() + node.scrollTop = 0 + } </script> {#snippet panelBody()} @@ -435,9 +442,10 @@ </div> </Pane> {#if panelMode === 'docked'} - <!-- Panels manage their own scrolling, so the pane must not scroll as well or a second - scrollbar appears beside theirs. `!` because splitpanes' own `overflow: auto` rule - has equal specificity and wins on cascade order. --> + <!-- The wrapper around the panel body scrolls, not the pane: scrolling the pane would + carry the placement strip away. A panel with its own scrolling must fill the wrapper + exactly, or a second scrollbar appears. `!` because splitpanes' own `overflow: auto` + rule has equal specificity and wins on cascade order. --> <Pane class="relative z-10 !overflow-hidden" size={50} minSize={20}> {#if loading} <div class="w-full h-full"> @@ -445,23 +453,21 @@ <WindmillIcon height="40px" width="40px" spin="fast" /> </div> </div> - {:else if modalPanel} + {:else} <div class="flex h-full flex-col"> <!-- Fallback for panels without a card header hosting the placement picker: a slim strip so moving the panel stays reachable. Toggled around a stable panelBody — re-parenting it would re-mount the claiming header and loop. --> - {#if detachClaims === 0} + {#if modalPanel && detachClaims === 0} <div class="flex items-center justify-end border-b px-1"> <FlowPanelPlacementPicker variant="header" /> </div> {/if} - <div class="min-h-0 flex-1"> + <div class="min-h-0 flex-1 overflow-auto" {@attach scrollToTopOnSelect}> {@render panelBody()} </div> </div> - {:else} - {@render panelBody()} {/if} </Pane> {/if} 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/FlowInputs.svelte b/frontend/src/lib/components/flows/content/FlowInputs.svelte index 41d860530a..7b72cac858 100644 --- a/frontend/src/lib/components/flows/content/FlowInputs.svelte +++ b/frontend/src/lib/components/flows/content/FlowInputs.svelte @@ -12,12 +12,16 @@ import { Check, Code, Zap } from 'lucide-svelte' import SuspendDrawer from './SuspendDrawer.svelte' import { defaultScripts } from '$lib/stores' + import { useRoleCapabilities } from '$lib/operatorWriteRights' import { defaultScriptLanguages, processInlineLangs } from '$lib/scripts' import type { SupportedLanguage } from '$lib/common' import DefaultScripts from '$lib/components/DefaultScripts.svelte' import type { FlowBuilderWhitelabelCustomUi } from '$lib/components/custom_ui' import { canHavePreprocessor } from '$lib/script_helpers' + const roleCaps = useRoleCapabilities() + const composeOnlyFlows = $derived($roleCaps.flows === 'compose') + interface Props { failureModule: boolean preprocessorModule: boolean @@ -51,6 +55,13 @@ ) let pick_existing: 'workspace' | 'hub' = $state('hub') let filter = $state('') + // The server adds a hub path only for a role that has code, whatever its flows level. + let showHub = $derived($roleCaps.code) + + // The pickers return no reliable kind, and the step's trigger or approval settings depend on it. + function pick(e: CustomEvent) { + dispatch('pick', { ...e.detail, kind: scriptKind }) + } let langs = $derived( processInlineLangs(undefined, $defaultScripts?.order ?? Object.keys(defaultScriptLanguages)) @@ -220,90 +231,93 @@ > {/if} {/if} - <h3 class="pb-2 pt-4 flex gap-x-8 flex-wrap"> - <div> - Inline new <span class="text-blue-500 dark:text-blue-400" - >{scriptKind == 'script' ? 'action' : scriptKind}</span + {#if !composeOnlyFlows} + <h3 class="pb-2 pt-4 flex gap-x-8 flex-wrap"> + <div> + Inline new <span class="text-blue-500 dark:text-blue-400" + >{scriptKind == 'script' ? 'action' : scriptKind}</span + > + script + <Tooltip + documentationLink={scriptKind === 'script' + ? 'https://www.windmill.dev/docs/flows/editor_components#flow-actions' + : scriptKind === 'trigger' + ? 'https://www.windmill.dev/docs/flows/flow_trigger' + : scriptKind === 'approval' + ? 'https://www.windmill.dev/docs/flows/flow_approval' + : scriptKind === 'preprocessor' + ? 'https://www.windmill.dev/docs/core_concepts/preprocessors' + : 'https://www.windmill.dev/docs/getting_started/flows_quickstart#flow-editor'} + > + Embed <span>{scriptKind == 'script' ? 'action' : scriptKind}</span> script directly inside + a flow instead of saving the script into your workspace for reuse. You can always save an + inline script to your workspace later. + </Tooltip> + </div> + <DefaultScripts /> + </h3> + {#if noEditor} + <div + class="py-0.5 text-2xs {summary == undefined || summary == '' + ? 'text-red-600' + : 'text-ternary'}" + >Pick a summary first, it will be used to create a separate file whose name will be + derived from the summary</div > - script - <Tooltip - documentationLink={scriptKind === 'script' - ? 'https://www.windmill.dev/docs/flows/editor_components#flow-actions' - : scriptKind === 'trigger' - ? 'https://www.windmill.dev/docs/flows/flow_trigger' - : scriptKind === 'approval' - ? 'https://www.windmill.dev/docs/flows/flow_approval' - : scriptKind === 'preprocessor' - ? 'https://www.windmill.dev/docs/core_concepts/preprocessors' - : 'https://www.windmill.dev/docs/getting_started/flows_quickstart#flow-editor'} - > - Embed <span>{scriptKind == 'script' ? 'action' : scriptKind}</span> script directly inside - a flow instead of saving the script into your workspace for reuse. You can always save an inline - script to your workspace later. - </Tooltip> + <input class="w-full" type="text" bind:value={summary} placeholder="Summary" /> + <div class="pb-2"></div> + {/if} + <div class="flex flex-row flex-wrap gap-2" id="flow-editor-action-script"> + {#each langs.filter((lang) => customUi?.languages == undefined || customUi?.languages?.includes(lang?.[1])) as [label, lang] (lang)} + {#if displayLang(lang, scriptKind)} + <FlowScriptPicker + id={`flow-editor-action-script-${lang}`} + disabled={noEditor && (summary == undefined || summary == '')} + {label} + lang={lang == 'docker' ? 'bash' : lang} + on:click={() => { + dispatch('new', { + language: lang == 'docker' ? 'bash' : lang, + kind: scriptKind, + subkind: + lang == 'docker' ? 'docker' : preprocessorModule ? 'preprocessor' : 'flow', + summary + }) + }} + /> + {/if} + {/each} </div> - <DefaultScripts /> - </h3> - {#if noEditor} - <div - class="py-0.5 text-2xs {summary == undefined || summary == '' - ? 'text-red-600' - : 'text-ternary'}" - >Pick a summary first, it will be used to create a separate file whose name will be derived - from the summary</div - > - <input class="w-full" type="text" bind:value={summary} placeholder="Summary" /> - <div class="pb-2"></div> - {/if} - <div class="flex flex-row flex-wrap gap-2" id="flow-editor-action-script"> - {#each langs.filter((lang) => customUi?.languages == undefined || customUi?.languages?.includes(lang?.[1])) as [label, lang] (lang)} - {#if displayLang(lang, scriptKind)} + + {#if !failureModule && !preprocessorModule && customUi?.aiSandbox != false} + <h3 class="pb-2 pt-4">AI Sandbox</h3> + <div class="flex flex-row flex-wrap gap-2"> <FlowScriptPicker - id={`flow-editor-action-script-${lang}`} - disabled={noEditor && (summary == undefined || summary == '')} - {label} - lang={lang == 'docker' ? 'bash' : lang} + label="Claude Code" + lang="claudesandbox" on:click={() => { dispatch('new', { - language: lang == 'docker' ? 'bash' : lang, - kind: scriptKind, - subkind: lang == 'docker' ? 'docker' : preprocessorModule ? 'preprocessor' : 'flow', + language: 'bun', + kind, + subkind: 'claudesandbox', summary }) }} /> - {/if} - {/each} - </div> - - {#if !failureModule && !preprocessorModule && customUi?.aiSandbox != false} - <h3 class="pb-2 pt-4">AI Sandbox</h3> - <div class="flex flex-row flex-wrap gap-2"> - <FlowScriptPicker - label="Claude Code" - lang="claudesandbox" - on:click={() => { - dispatch('new', { - language: 'bun', - kind, - subkind: 'claudesandbox', - summary - }) - }} - /> - <FlowScriptPicker - label="Pi" - lang="pisandbox" - on:click={() => { - dispatch('new', { - language: 'bun', - kind, - subkind: 'pisandbox', - summary - }) - }} - /> - </div> + <FlowScriptPicker + label="Pi" + lang="pisandbox" + on:click={() => { + dispatch('new', { + language: 'bun', + kind, + subkind: 'pisandbox', + summary + }) + }} + /> + </div> + {/if} {/if} <h3 class="mb-2 mt-6" @@ -313,14 +327,16 @@ > {#if preprocessorModule} <!-- The hub publishes no preprocessor script, so this slot only ever picks from the workspace. --> - <WorkspaceScriptPicker displayLock bind:filter kind="preprocessor" on:pick /> - {:else if pick_existing == 'hub'} - <PickHubScript bind:filter {kind} on:pick> + <WorkspaceScriptPicker displayLock bind:filter kind="preprocessor" on:pick={pick} /> + {:else if showHub && pick_existing == 'hub'} + <PickHubScript bind:filter {kind} on:pick={pick}> <ToggleHubWorkspace bind:selected={pick_existing} /> </PickHubScript> {:else} - <WorkspaceScriptPicker displayLock bind:filter {kind} on:pick> - <ToggleHubWorkspace bind:selected={pick_existing} /> + <WorkspaceScriptPicker displayLock bind:filter {kind} on:pick={pick}> + {#if showHub} + <ToggleHubWorkspace bind:selected={pick_existing} /> + {/if} </WorkspaceScriptPicker> {/if} {/if} 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/FlowModuleWrapper.svelte b/frontend/src/lib/components/flows/content/FlowModuleWrapper.svelte index af1ff81eaa..20d4fb6968 100644 --- a/frontend/src/lib/components/flows/content/FlowModuleWrapper.svelte +++ b/frontend/src/lib/components/flows/content/FlowModuleWrapper.svelte @@ -108,7 +108,7 @@ summary, flowModule.id, hash, - undefined, + kind, opWorkspace?.() ) 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/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..c847f89fee 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, @@ -283,6 +286,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..da716689c7 100644 --- a/frontend/src/lib/components/home/RecentRunRow.svelte +++ b/frontend/src/lib/components/home/RecentRunRow.svelte @@ -1,7 +1,15 @@ <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, + Loader2, + Wrench + } from 'lucide-svelte' import { Button } from '$lib/components/common' import DropdownV2 from '$lib/components/DropdownV2.svelte' import { useRoleCapabilities } from '$lib/operatorWriteRights' @@ -55,14 +63,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) { @@ -103,6 +115,10 @@ <span class="flex w-3.5 shrink-0 justify-center"> {#if item.status === 'running'} <Loader2 size={14} class="animate-spin text-yellow-500" /> + {: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 +235,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/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/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/raw_apps/RawAppEditor.svelte b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte index 20c3ff1e74..d209f4da1e 100644 --- a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte @@ -39,7 +39,7 @@ applyRawAppStorageOp } 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 +86,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 +302,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( @@ -2212,7 +2211,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 +3180,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/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..4366857f6b 100644 --- a/frontend/src/lib/components/runs/JobStatusIcon.svelte +++ b/frontend/src/lib/components/runs/JobStatusIcon.svelte @@ -6,7 +6,9 @@ Calendar, Check, FastForward, + Gauge, Hourglass, + Moon, Play, ShieldQuestion, Wrench, @@ -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,10 +77,32 @@ <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} /> </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'}> <Calendar size={14} /> 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/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/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..19d11d1fc5 100644 --- a/frontend/src/lib/components/sessions/SessionWrapper.svelte +++ b/frontend/src/lib/components/sessions/SessionWrapper.svelte @@ -61,7 +61,7 @@ getSessionDraftAttachments, setSessionDraftAttachments, peekSessionAutoSend, - getSessionAutoSendDomElement, + getSessionAutoSendPick, takeSessionAutoSend, reconcileAfterWorkspaceChange, renameSession, @@ -192,14 +192,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/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/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/triggers/CaptureSection.svelte b/frontend/src/lib/components/triggers/CaptureSection.svelte index 4fa2fab5fb..2df509f95c 100644 --- a/frontend/src/lib/components/triggers/CaptureSection.svelte +++ b/frontend/src/lib/components/triggers/CaptureSection.svelte @@ -36,12 +36,13 @@ import { FlaskConical } from 'lucide-svelte' import Alert from '../common/alert/Alert.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' - import { useTriggerLock } from '$lib/operatorWriteRights' + import { useRoleCapabilities, useTriggerLock } from '$lib/operatorWriteRights' const operatingWorkspace = useOperatingWorkspace() // Saving a capture config is a trigger write the server refuses to a withdrawn operator, so // every capture kind locks here rather than each editor passing it down. const triggerLock = useTriggerLock() + const roleCaps = useRoleCapabilities() interface Props { disabled?: boolean | undefined @@ -67,6 +68,9 @@ displayAlert = false }: Props = $props() + // The button inserts an inline script, which the server refuses in a compose-only role's flow. + const canAddInlinePreprocessor = $derived(!captureInfo.isFlow || $roleCaps.flows !== 'compose') + const testKind: 'preprocessor' | 'main' = $derived(hasPreprocessor ? 'preprocessor' : 'main') const dispatch = createEventDispatcher<{ @@ -482,7 +486,8 @@ <Alert type="info" title="Raw payload displayed" size="xs" class="mt-2 mb-2"> <div class="flex flex-col gap-2"> <div> - Add a preprocessor to use the raw payload data in the flow. + Add a preprocessor{canAddInlinePreprocessor ? '' : ' from the flow graph'} to use + the raw payload data in the flow. <a href="https://www.windmill.dev/docs/core_concepts/preprocessors" target="_blank" @@ -493,24 +498,26 @@ <ExternalLink size={12} class="inline-block" /> </a> </div> - <div class="flex justify-end"> - <Button - size="xs" - variant="accent" - wrapperClasses="w-fit" - onclick={() => { - if (selectedCapture) { - dispatch('addPreprocessor', { - args: $state.snapshot(payloadData) - }) - } else { - dispatch('addPreprocessor') - } - }} - > - Add preprocessor - </Button> - </div> + {#if canAddInlinePreprocessor} + <div class="flex justify-end"> + <Button + size="xs" + variant="accent" + wrapperClasses="w-fit" + onclick={() => { + if (selectedCapture) { + dispatch('addPreprocessor', { + args: $state.snapshot(payloadData) + }) + } else { + dispatch('addPreprocessor') + } + }} + > + Add preprocessor + </Button> + </div> + {/if} </div> </Alert> {/if} 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/stores.ts b/frontend/src/lib/stores.ts index 16b62da863..4e27fade37 100644 --- a/frontend/src/lib/stores.ts +++ b/frontend/src/lib/stores.ts @@ -218,6 +218,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/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)/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/(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)/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/lsp/Pipfile b/lsp/Pipfile index 350454782d..0f80843668 100644 --- a/lsp/Pipfile +++ b/lsp/Pipfile @@ -4,7 +4,7 @@ verify_ssl = true name = "pypi" [packages] -wmill = ">=1.884.1" +wmill = ">=1.885.0" sendgrid = "*" mysql-connector-python = "*" pymongo = "*" diff --git a/openflow.openapi.yaml b/openflow.openapi.yaml index fce7e70671..525a8e7177 100644 --- a/openflow.openapi.yaml +++ b/openflow.openapi.yaml @@ -1,7 +1,7 @@ openapi: '3.0.3' info: - version: 1.884.1 + version: 1.885.0 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) @@ -1528,6 +1534,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..d60fd0016b 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.885.0' # Supported PSEditions # CompatiblePSEditions = @() diff --git a/python-client/wmill/pyproject.toml b/python-client/wmill/pyproject.toml index 586ce6fa11..c13407604b 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.885.0" 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..f8ca5b8958 100644 --- a/system_prompts/auto-generated/cli/cli-commands.md +++ b/system_prompts/auto-generated/cli/cli-commands.md @@ -325,6 +325,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 +348,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-...) diff --git a/system_prompts/auto-generated/flow.md b/system_prompts/auto-generated/flow.md index 9c7a67f8eb..200b4c1ff0 100644 --- a/system_prompts/auto-generated/flow.md +++ b/system_prompts/auto-generated/flow.md @@ -631,4 +631,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"},"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"},"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..229326cc50 100644 --- a/system_prompts/auto-generated/prompts.ts +++ b/system_prompts/auto-generated/prompts.ts @@ -1633,7 +1633,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. | @@ -4110,7 +4110,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"},"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"},"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 @@ -4439,6 +4439,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 +4462,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-...) diff --git a/system_prompts/auto-generated/skills/cli-commands/SKILL.md b/system_prompts/auto-generated/skills/cli-commands/SKILL.md index 87691caffb..2177fd5523 100644 --- a/system_prompts/auto-generated/skills/cli-commands/SKILL.md +++ b/system_prompts/auto-generated/skills/cli-commands/SKILL.md @@ -330,6 +330,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 +353,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-...) 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..732e4dea4f 100644 --- a/system_prompts/auto-generated/skills/write-flow/SKILL.md +++ b/system_prompts/auto-generated/skills/write-flow/SKILL.md @@ -719,4 +719,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"},"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"},"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/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/jsr.json b/typescript-client/jsr.json index 36bbfb5a2d..d474f81115 100644 --- a/typescript-client/jsr.json +++ b/typescript-client/jsr.json @@ -1,6 +1,6 @@ { "name": "@windmill/windmill", - "version": "1.884.1", + "version": "1.885.0", "exports": "./src/index.ts", "publish": { "exclude": ["!src", "./s3Types.ts", "./sqlUtils.ts", "./client.ts", "./wacError.ts"] diff --git a/typescript-client/package.json b/typescript-client/package.json index f6ad0a6798..ae175dddb6 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.885.0", "author": "Ruben Fiszel", "license": "Apache 2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/typescript-client#readme", diff --git a/version.txt b/version.txt index 2b25752d80..5d0920caf0 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.884.1 +1.885.0 diff --git a/windmill-yaml-validator/package-lock.json b/windmill-yaml-validator/package-lock.json index af40b2ff17..a02b74070d 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.885.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "windmill-yaml-validator", - "version": "1.884.1", + "version": "1.885.0", "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..ebba8865c0 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.885.0", "description": "YAML validator for Windmill flow, schedule, and trigger files", "main": "dist/index.js", "types": "dist/index.d.ts",