mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-28 08:06:16 +00:00
Merge origin/main into access-view-read-only
This commit is contained in:
@@ -36,6 +36,10 @@ WMILL_AI_EVAL_BACKEND_URL=http://127.0.0.1:<port> WMILL_AI_EVAL_BACKEND_WORKSPAC
|
||||
`WMILL_AI_EVAL_BACKEND_WORKSPACE=integration-tests` (or any existing workspace) to
|
||||
reuse one. The only side effect of a run is upserting an `f/evals/ai/<provider>`
|
||||
resource there.
|
||||
- **Global mode creates its own workspace per attempt** and seeds the case's fixture in it,
|
||||
because the session's tools run on the backend; it ignores
|
||||
`WMILL_AI_EVAL_BACKEND_WORKSPACE` and needs a `postgresql` (native) worker for datatable
|
||||
cases. `ai_evals/README.md` ("Global mode runs against a real workspace") lists the rest.
|
||||
- Provider keys live in `ai_evals/.env` and are auto-loaded by bun. The judge is a
|
||||
separate Anthropic call (default `claude-sonnet-4-6`) regardless of the model under
|
||||
test.
|
||||
|
||||
@@ -105,16 +105,25 @@ jobs:
|
||||
SQLX_OFFLINE: true
|
||||
CARGO_BUILD_JOBS: 12
|
||||
RUSTFLAGS: ""
|
||||
run: cargo build --features quickjs
|
||||
# The global suite's hub cases search the hub embeddings index; its trigger cases
|
||||
# write HTTP triggers, whose routes the feature mounts.
|
||||
run: cargo build --features quickjs,embedding,http_trigger
|
||||
|
||||
- name: Start Windmill
|
||||
working-directory: ./backend
|
||||
env:
|
||||
DATABASE_URL: postgres://postgres:changeme@localhost:5432/windmill
|
||||
RUST_LOG: info
|
||||
# Each global case seeds resource types and waits until the search indexes them.
|
||||
RESOURCE_TYPE_EMBEDDINGS_CHECK_INTERVAL_SECS: "2"
|
||||
run: |
|
||||
mkdir -p ../ai_evals/logs
|
||||
# A model may test-run the script it drafts; the worker looks for bun at /usr/bin/bun,
|
||||
# where setup-bun does not put it.
|
||||
export BUN_PATH="$(command -v bun)"
|
||||
./target/debug/windmill > ../ai_evals/logs/windmill.log 2>&1 &
|
||||
# The global suite's datatable cases run SQL on the `postgresql` tag, a native worker's.
|
||||
MODE=worker WORKER_GROUP=native PORT=8001 ./target/debug/windmill > ../ai_evals/logs/windmill-native.log 2>&1 &
|
||||
for i in $(seq 1 60); do
|
||||
curl -sf http://localhost:8000/api/version > /dev/null 2>&1 && break
|
||||
sleep 2
|
||||
@@ -142,6 +151,8 @@ jobs:
|
||||
MODEL: ${{ matrix.model }}
|
||||
WMILL_AI_EVAL_BACKEND_URL: http://localhost:8000
|
||||
WMILL_AI_EVAL_BACKEND_WORKSPACE: integration-tests
|
||||
# Global fixtures whose user is not the admin are created in the backend's database.
|
||||
WMILL_AI_EVAL_DATABASE_URL: postgres://postgres:changeme@localhost:5432/windmill
|
||||
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
GEMINI_API_KEY: ${{ secrets.GOOGLE_API_KEY }}
|
||||
|
||||
@@ -3,8 +3,9 @@ name: AI Evals (global mode)
|
||||
# Smoke-tests the production global AI chat proxy/frontend execution path via
|
||||
# the ai_evals harness, one case across one cheap model per provider. Runs only
|
||||
# when the eval harness or the global chat code change, since each run makes real
|
||||
# (paid) LLM calls. The backend is built from source purely as the AI proxy the
|
||||
# harness routes model calls through; the global tools/drafts run in-process in
|
||||
# (paid) LLM calls. The backend is built from source as the AI proxy the harness
|
||||
# routes model calls through and as the server the global tools run on, in a
|
||||
# workspace the harness creates per attempt; the chat itself runs in-process in
|
||||
# the Vitest bridge against production frontend code. To avoid spending on every
|
||||
# commit, the PR side triggers only when a PR is marked ready for review (out of
|
||||
# draft) — not on `synchronize` — plus push to main and manual dispatch.
|
||||
@@ -15,6 +16,7 @@ on:
|
||||
paths:
|
||||
- "ai_evals/**"
|
||||
- "backend/windmill-api/src/ai.rs"
|
||||
- "backend/windmill-api/src/ai_session_tools/**"
|
||||
- "backend/windmill-ai/**"
|
||||
- "frontend/src/lib/components/copilot/**"
|
||||
# The eval harness runs production frontend code in-process; these are the
|
||||
@@ -29,6 +31,7 @@ on:
|
||||
paths:
|
||||
- "ai_evals/**"
|
||||
- "backend/windmill-api/src/ai.rs"
|
||||
- "backend/windmill-api/src/ai_session_tools/**"
|
||||
- "backend/windmill-ai/**"
|
||||
- "frontend/src/lib/components/copilot/**"
|
||||
# The eval harness runs production frontend code in-process; these are the
|
||||
@@ -103,7 +106,11 @@ jobs:
|
||||
RUST_LOG: info
|
||||
run: |
|
||||
mkdir -p ../ai_evals/logs
|
||||
# A model may test-run the script it drafts. The worker looks for bun at /usr/bin/bun,
|
||||
# where setup-bun does not put it, and `//native` scripts run on a native worker's tag.
|
||||
export BUN_PATH="$(command -v bun)"
|
||||
./target/debug/windmill > ../ai_evals/logs/windmill.log 2>&1 &
|
||||
MODE=worker WORKER_GROUP=native PORT=8001 ./target/debug/windmill > ../ai_evals/logs/windmill-native.log 2>&1 &
|
||||
echo "Waiting for Windmill to be ready..."
|
||||
for i in $(seq 1 60); do
|
||||
if curl -sf http://localhost:8000/api/version > /dev/null 2>&1; then
|
||||
@@ -137,6 +144,8 @@ jobs:
|
||||
env:
|
||||
WMILL_AI_EVAL_BACKEND_URL: http://localhost:8000
|
||||
WMILL_AI_EVAL_BACKEND_WORKSPACE: integration-tests
|
||||
# Global fixtures whose user is not the admin are created in the backend's database.
|
||||
WMILL_AI_EVAL_DATABASE_URL: postgres://postgres:changeme@localhost:5432/windmill
|
||||
# Anthropic backs the haiku model. Google AI uses GEMINI_API_KEY.
|
||||
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
|
||||
@@ -71,6 +71,7 @@ jobs:
|
||||
docker run -d --name windmill-extra-test \
|
||||
-p 3001:3001 -p 3002:3002 -p 3003:3003 \
|
||||
-e ENABLE_LSP=true \
|
||||
-e REQUIRE_SIGNED_LSP_REQUESTS=false \
|
||||
-e ENABLE_MULTIPLAYER=true \
|
||||
-e ENABLE_DEBUGGER=true \
|
||||
-e DEBUGGER_PORT=3003 \
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "1.856.0"
|
||||
".": "1.858.0"
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ Open-source platform for internal tools, workflows, API integrations, background
|
||||
- **Domain vocabulary**: `CONTEXT.md` — the words this codebase uses for its own concepts (step, step setting, trigger step, …). Name things the way it does.
|
||||
- **CLI commands**: when adding/modifying/removing a command, subcommand, option, or description in `cli/src/commands/`, run `python system_prompts/generate.py` to refresh `system_prompts/auto-generated/` and `cli/src/guidance/skills.gen.ts`. The CLI docs the agents use to operate `wmill` are derived from the source — stale generated files give agents the wrong flags.
|
||||
- **AI guidance** (chat prompts and CLI skills): what the AI knows about Windmill itself — how flows, scripts, apps, pipelines and resources work — is written once, in `system_prompts/base/` and `system_prompts/languages/`, and `system_prompts/generate.py` builds both the chat's `$system_prompts` exports and the CLI's skills from it. Add or change such guidance there, never inline in one consumer: a sentence only one side should see goes in a `<!-- cli-only -->` / `<!-- chat-only -->` block, and a new file reaches both through the `TOPICS` table. The chat prompt builders under `frontend/src/lib/components/copilot/chat/` add only tool plumbing and runtime values, and shared markdown names no chat tool, since it reaches every chat mode. Rerun `generate.py` after editing; `system_prompts/README.md` has the details.
|
||||
- **Windmill MCP server**: `/api/mcp` gives a token with `mcp:all` the AI session's GLOBAL toolset (`backend/windmill-api/src/mcp/session/`), and a token scoped to a selection of scripts and flows the tools server's per-runnable tools, without endpoint tools. The tools server's own URLs, `/api/mcp/w/{workspace}/mcp` and `/api/mcp/gateway`, keep serving existing tokens, endpoint scopes included, except that they give the session toolset to an `mcp:all` token carrying `mcp:session` (added by the OAuth approve, kept across scope edits) or `mcp:read_only`/`mcp:read_run`. Every tool takes a `workspace_id`; the token bounds which (its bound workspace, the `mcp:workspaces:` list, or all of its owner's). With the `mcp_external_idp` instance setting, every MCP URL also accepts an access token of an external OIDC issuer (`mcp/external_idp.rs`), told apart from Windmill's own by its `iss`: the token's client is mapped to a workspace and to the same access a Windmill token takes (an access level, served the session toolset as `mcp:session`, or a selection of scripts and flows), and the request acts as the existing Windmill user with the token's email, under that access, as a workspace-bound token does. The protected-resource metadata then names that issuer. What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `session/gen/`: after changing a GLOBAL tool definition, the global system prompt or `system_prompts/`, run `npm run gen:mcp-session` from `frontend/` (`mcpSessionGen.test.ts` fails otherwise). What a tool *does* is written twice, in `chat/global/core.ts` and in a Rust handler: a behaviour change on one side must be mirrored on the other, and a new session tool is either implemented in Rust or added to `EDITOR_ONLY` (a `cargo test` in `session/mod.rs` fails otherwise). For MCP Apps clients the server adds tools of its own, defined in Rust (`session/views.rs`) rather than generated: `show_run`, `show_runs`, `show_deploy_review` and `show_item` draw a card in the `ui://windmill/card-v<N>` view (`session/card.html`; bump `CARD_URI` when the `_meta` it reads changes shape, since hosts cache a view by URI) from their result's `_meta` (`windmill/run`, `windmill/runs`, `windmill/review`, `windmill/item`), which the model never reads. A host draws a card for every call of a tool that declares one, so only these show tools do: the tools the model reads and runs with draw nothing, and `get_run` builds no card data. The card acts only by calling the session's tools (`show_run` to refresh, `cancel_job`, `show_deploy_review` to re-read a draft, `deploy_workspace_item` from the review card's Deploy button, which the user presses), so it sees nothing the model could not. Every `DESTRUCTIVE` tool but those in `CARD_ACTIONS` is hidden from it. Every session tool carries a `title` and explicit read-only, destructive and open-world hints, which the Claude and ChatGPT directories require (`DESTRUCTIVE`, `OPEN_WORLD`). A client that declares capabilities without the MCP Apps extension is not offered the show tools. It exists only on the MCP side, so `core.ts` has nothing to mirror.
|
||||
- **Windmill MCP server**: `/api/mcp` gives a token with `mcp:all` the AI session's GLOBAL toolset (`backend/windmill-api/src/ai_session_tools/`), and a token scoped to a selection of scripts and flows the tools server's per-runnable tools, without endpoint tools. The tools server's own URLs, `/api/mcp/w/{workspace}/mcp` and `/api/mcp/gateway`, keep serving existing tokens, endpoint scopes included, except that they give the session toolset to an `mcp:all` token carrying `mcp:session` (added by the OAuth approve, kept across scope edits) or `mcp:read_only`/`mcp:read_run`. Every tool takes a `workspace_id`; the token bounds which (its bound workspace, the `mcp:workspaces:` list, or all of its owner's). With the `mcp_external_idp` instance setting, every MCP URL also accepts an access token of an external OIDC issuer (`mcp/external_idp.rs`), told apart from Windmill's own by its `iss`: the token's client is mapped to a workspace and to the same access a Windmill token takes (an access level, served the session toolset as `mcp:session`, or a selection of scripts and flows), and the request acts as the existing Windmill user with the token's email, under that access, as a workspace-bound token does. The protected-resource metadata then names that issuer. What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `ai_session_tools/gen/`: after changing a GLOBAL tool definition, the global system prompt or `system_prompts/`, run `npm run gen:mcp-session` from `frontend/` (`mcpSessionGen.test.ts` fails otherwise). What a tool *does* is written once, in a Rust handler the chat also calls (`POST /w/{workspace}/ai_session_tools/{name}`, through `chat/global/backendSessionTools.ts`); the browser applies the effects it returns, saving drafts through its own draft store. A new session tool is either implemented in Rust or added to `EDITOR_ONLY` (a `cargo test` in `ai_session_tools/mod.rs` fails otherwise). Still written twice, so a behaviour change must be mirrored: `deploy_workspace_item` and `diff` (the chat uses the UI's shared deploy and diff code), and the run tools' form side (argument coercion, secrets, plan mode, the outcome text), where the chat resolves and starts the run on the server but owns the form in between; both sides test their argument handling against `ai_session_tools/run_args_cases.json`, so a change there comes with a case. For MCP Apps clients the server adds tools of its own, defined in Rust (`ai_session_tools/views.rs`) rather than generated, and not offered to the chat, which draws its own cards: `show_run`, `show_runs`, `show_deploy_review` and `show_item` draw a card in the `ui://windmill/card-v<N>` view (`mcp/card.html`; bump `CARD_URI` in `mcp/session.rs` when the `_meta` it reads changes shape, since hosts cache a view by URI) from their result's `_meta` (`windmill/run`, `windmill/runs`, `windmill/review`, `windmill/item`), which the model never reads. A host draws a card for every call of a tool that declares one, so only these show tools do: the tools the model reads and runs with draw nothing, and `get_run` builds no card data. The card acts only by calling the session's tools (`show_run` to refresh, `cancel_job`, `show_deploy_review` to re-read a draft, `deploy_workspace_item` from the review card's Deploy button, which the user presses), so it sees nothing the model could not. Every `DESTRUCTIVE` tool but those in `CARD_ACTIONS` is hidden from it. Every session tool carries a `title` and explicit read-only, destructive and open-world hints, which the Claude and ChatGPT directories require (`DESTRUCTIVE`, `OPEN_WORLD`). A client that declares capabilities without the MCP Apps extension is not offered the show tools.
|
||||
- **Session recorder**: `frontend/src/lib/components/recording/` is also the recorder `wmill app dev --recording` serves, vendored into the CLI as `cli/src/commands/app/devRecorderBundle.gen.ts`. After changing `rawAppSnapshot.ts` or `rawAppRecording.svelte.ts`, run `bun run gen:dev-recorder` from `cli/` (`cli/test/dev_recorder_bundle_unit.test.ts` fails otherwise).
|
||||
- **Raw-app policy**: `frontend/src/lib/components/raw_apps/rawAppPolicy.ts` also derives the policy the server's raw-app deploy stores, vendored into the bundle job as `backend/windmill-api/src/apps_raw_policy.gen.js`. After changing it or anything it imports, run `bun run gen:app-policy` from `cli/` (`cli/test/app_policy_bundle_unit.test.ts` fails otherwise). It rides in the job rather than being read from the CLI the job runs because the images install `windmill-cli` unpinned, so an image can carry one older than its server.
|
||||
|
||||
|
||||
@@ -1,5 +1,39 @@
|
||||
# Changelog
|
||||
|
||||
## [1.858.0](https://github.com/windmill-labs/windmill/compare/v1.857.0...v1.858.0) (2026-11-03)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* resolved runs on home, an easier resolve action, and load fades ([#12167](https://github.com/windmill-labs/windmill/issues/12167)) ([1a6e544](https://github.com/windmill-labs/windmill/commit/1a6e5440ba02ef9ce9984dbc10d274f796b2703d))
|
||||
|
||||
## [1.857.0](https://github.com/windmill-labs/windmill/compare/v1.856.0...v1.857.0) (2026-11-03)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add a recently run panel to the workspace home ([#12105](https://github.com/windmill-labs/windmill/issues/12105)) ([d1a2c13](https://github.com/windmill-labs/windmill/commit/d1a2c13cf27f6e1ad920310b80ebede25acb4d98))
|
||||
* add home's folders, users and cards to the ai session context ([#12104](https://github.com/windmill-labs/windmill/issues/12104)) ([263088a](https://github.com/windmill-labs/windmill/commit/263088a8ac718823859e2909db70129b86f829e4))
|
||||
* name a materialized table after its script when the target names none ([#12157](https://github.com/windmill-labs/windmill/issues/12157)) ([116c902](https://github.com/windmill-labs/windmill/commit/116c90280e8fe59a6f0b1b186c109066c894165b))
|
||||
* publish a folder sub-path to the Hub as its own project ([#12081](https://github.com/windmill-labs/windmill/issues/12081)) ([23fbf1e](https://github.com/windmill-labs/windmill/commit/23fbf1edfe62339eaff2b576aeea32d81e37d97b))
|
||||
* upgrade the bundled DuckDB engine to 2.0.0 LTS ([#11924](https://github.com/windmill-labs/windmill/issues/11924)) ([3d0ca92](https://github.com/windmill-labs/windmill/commit/3d0ca92ef2ad98b1c3e5abe68a7a5b10c94f05df))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* order ai sessions by their last turn instead of creation time ([#12147](https://github.com/windmill-labs/windmill/issues/12147)) ([b451e8e](https://github.com/windmill-labs/windmill/commit/b451e8edca6a8fb8de1de442879147a8163a7543))
|
||||
* parse runnable references once at the API run entry points ([#12153](https://github.com/windmill-labs/windmill/issues/12153)) ([088c83e](https://github.com/windmill-labs/windmill/commit/088c83e3f89bd151980e6363e556e69f6745bc03))
|
||||
* reserve the username anonymous used by logged-out visitors ([#12146](https://github.com/windmill-labs/windmill/issues/12146)) ([2aa6059](https://github.com/windmill-labs/windmill/commit/2aa6059e58e1cf4708ba65927d6e6338d364127a))
|
||||
* scope user deletion's group cleanup to its workspaces ([#12145](https://github.com/windmill-labs/windmill/issues/12145)) ([66be711](https://github.com/windmill-labs/windmill/commit/66be711dbd47a1ac8c066b8e1f323c982fa7e7bc))
|
||||
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* load click-only features after the app shell paints ([#12161](https://github.com/windmill-labs/windmill/issues/12161)) ([3481adf](https://github.com/windmill-labs/windmill/commit/3481adf3dca9de201f729174da00184d72ad1829))
|
||||
* paint a snapshot of the last home in place of the boot splash ([#12158](https://github.com/windmill-labs/windmill/issues/12158)) ([0ac2b61](https://github.com/windmill-labs/windmill/commit/0ac2b6103452dc69201fe8a7d1107095e10fac97))
|
||||
* paint home from a persisted cache and the last confirmed user ([#12154](https://github.com/windmill-labs/windmill/issues/12154)) ([2d10518](https://github.com/windmill-labs/windmill/commit/2d105189b2e4b226ce78475790ca4f291781f9ca))
|
||||
* stop vite's preload helper from rescanning every link per dependency ([#12155](https://github.com/windmill-labs/windmill/issues/12155)) ([40cb945](https://github.com/windmill-labs/windmill/commit/40cb945a1acc96d4c0664fb2e91806785a260776))
|
||||
|
||||
## [1.856.0](https://github.com/windmill-labs/windmill/compare/v1.855.1...v1.856.0) (2026-11-02)
|
||||
|
||||
|
||||
|
||||
+67
-23
@@ -170,13 +170,69 @@ chose in the artifact's version picker — which only `get_preview_status` repor
|
||||
|
||||
Global initial fixtures can seed `workspace.variables` with
|
||||
`{ path, value, is_secret, description?, labels?, ws_specific? }` entries so cases can
|
||||
read and edit variables that already exist in the workspace. The mock mirrors the real
|
||||
`get_variable`, **decrypt-by-default included**: a secret's `value` is withheld only
|
||||
when the caller explicitly passes `decryptSecret: false`, and omitting the flag returns
|
||||
the decrypted value, exactly as against a real backend. The chat's read path passes
|
||||
`decryptSecret: false`, so a case can verify it never invents a value it was not shown.
|
||||
Seed a recognizable secret (the existing fixture uses `sk_live_do_not_leak_me`) and
|
||||
assert it via `valueExcludes` to catch a leak.
|
||||
read and edit variables that already exist in the workspace. Seed a recognizable secret
|
||||
(the existing fixture uses `sk_live_do_not_leak_me`) and assert it via `valueExcludes` to
|
||||
catch a leak.
|
||||
|
||||
### Global mode runs against a real workspace
|
||||
|
||||
The session's tools run on the backend, so each global attempt creates its own workspace on
|
||||
the eval backend, seeds the fixture there through the API, and deletes it afterwards. What
|
||||
that backend needs:
|
||||
|
||||
- a worker serving the `postgresql` tag (the `native` group) for datatable fixtures and the
|
||||
SQL tools, and `WMILL_AI_EVAL_DATATABLE_PG_URL` (default
|
||||
`postgres://postgres:changeme@localhost:5432/postgres`) naming a Postgres the worker can
|
||||
reach, where each datatable fixture gets a scratch database;
|
||||
- a superadmin login (the default `admin@windmill.dev`), since it creates and deletes
|
||||
workspaces. `WMILL_AI_EVAL_BACKEND_WORKSPACE` does not apply to global mode. A CE backend
|
||||
allows two workspaces besides `admins`, so attempts past that wait for a free slot;
|
||||
- `WMILL_AI_EVAL_DATABASE_URL`, the eval backend's own database, for fixtures whose `user` is
|
||||
not the admin: the harness writes that user and a token of theirs there with `psql` (CE cannot create
|
||||
users through the API), adds them to the workspace, and revokes the token afterwards;
|
||||
- network access to the hub, which the hub tools reach through the backend, and the
|
||||
`embedding` cargo feature, without which `search_hub_scripts` has no index to search;
|
||||
- the `http_trigger` cargo feature, which mounts the routes HTTP trigger drafts are checked
|
||||
against;
|
||||
- `RESOURCE_TYPE_EMBEDDINGS_CHECK_INTERVAL_SECS` set low (CI uses 2): each attempt seeds the
|
||||
hub's resource types into its workspace and waits until the resource type search sees them,
|
||||
which takes up to that interval (60 s by default).
|
||||
|
||||
#### Running the pipeline a case built
|
||||
|
||||
A case with `validate.pipelineRun` runs the data pipeline the chat drafted, once the chat is
|
||||
over. The harness deploys every pipeline node drafted under `f/<folder>/`, waits for the
|
||||
deployments, points each DuckLake at an empty catalog, runs the nodes that no other node
|
||||
feeds, and waits for the asset triggers to run the rest. Then it runs the case's `queries`
|
||||
(DuckDB, with the lake attached as `dl`) and checks their rows. A node that never ran fails
|
||||
its check, so a downstream node whose `on` wiring is wrong cannot pass on the tables the
|
||||
model's own test runs left behind. A node is started directly when no recorded read or
|
||||
trigger ties it to another node's output, which also happens when the asset parser records a
|
||||
read under another path than the write it matches; `maxRoots` caps how many nodes may start
|
||||
that way. The run's outcome is part of the drafts the judge reads.
|
||||
|
||||
The fixture's `workspace.objectStorage` gives the workspace an S3 storage holding its
|
||||
`files`, and turns its `ducklakes` into catalogs on that storage. That needs more of the
|
||||
backend:
|
||||
|
||||
- the `duckdb`, `parquet` and `private` cargo features, and the DuckDB runner
|
||||
(`backend/windmill-duckdb-ffi-internal/build_dev.sh`). `private` provides the S3 proxy
|
||||
DuckDB reaches the storage through. A CE build without a license key is enough;
|
||||
- an S3-compatible store with an existing bucket: `WMILL_AI_EVAL_S3_ENDPOINT` (e.g.
|
||||
`http://localhost:9000`), `WMILL_AI_EVAL_S3_BUCKET` (default `evals`),
|
||||
`WMILL_AI_EVAL_S3_ACCESS_KEY` / `WMILL_AI_EVAL_S3_SECRET_KEY` (default `minioadmin`) and
|
||||
`WMILL_AI_EVAL_S3_REGION` (default `us-east-1`). Attempts share the bucket and seed the same
|
||||
keys; each one's DuckLake data goes under `ai_evals_lakes/<workspace>/`, which nothing
|
||||
deletes. MinIO, or `docker run -p 8333:8333 chrislusf/seaweedfs server -s3` (any key, and
|
||||
`curl -X PUT localhost:8333/evals` creates the bucket), both work.
|
||||
|
||||
Without `WMILL_AI_EVAL_S3_ENDPOINT` the run is skipped with a warning, and the case is
|
||||
checked on its drafts and judge alone.
|
||||
|
||||
A fixture's `jobs` become completed preview runs with the given id, path, args, logs and
|
||||
outcome; `createdBy` is not reproduced. Its `resourceTypes` are created as workspace types,
|
||||
alongside whatever types the instance already holds; a fixture that sets none gets the types
|
||||
of an instance synced with the hub.
|
||||
|
||||
`runtime.userAnswers` scripts the user's side of `askUserQuestion` in a global case: one
|
||||
answer per question, in the order they are asked, and a question past the last answer is
|
||||
@@ -213,24 +269,12 @@ recorded call to that tool may pass the field at all (an explicit `null` counts
|
||||
passing it). Use it for partial-update tools, where supplying a field the model could
|
||||
not have read is itself the failure — e.g. `write_variable.value` on a secret variable.
|
||||
|
||||
Global (and flow) initial fixtures can seed `workspace.datatables` so the
|
||||
`list_datatables`, `get_datatable_table_schema`, and `exec_datatable_sql` tools
|
||||
return seeded data during evals. Each entry is
|
||||
Global initial fixtures can seed `workspace.datatables`. Each entry is
|
||||
`{ datatable_name, schemas: { <schema>: { <table>: { columns, rows? } } } }`,
|
||||
plus `migrations_enabled: true` and `migrations: [{ timestamp, name, code_up, code_down?, applied? }]`
|
||||
for a datatable that keeps its schema as migrations, which the migration tools then
|
||||
read and write in memory.
|
||||
SQL runs through a small in-memory engine (`datatableSqlEngine.ts`), not a real
|
||||
database. Writes are **stateful within a case**: `CREATE`/`DROP`/`INSERT`/`UPDATE`/
|
||||
`DELETE` mutate the seeded datatable in place, so a later `list_datatables`,
|
||||
`get_datatable_table_schema`, `SELECT`, or `information_schema` query reflects them
|
||||
— this is what stops a model from looping when it re-queries to verify a write.
|
||||
The engine is best-effort: `SELECT` returns all rows of the referenced (or first)
|
||||
table with no WHERE filtering/projection/joins, `WHERE` on UPDATE/DELETE supports
|
||||
`col = value` predicates joined by `AND`, and anything unparseable is a no-op
|
||||
success. So validate datatable cases through tool-use and SQL-argument assertions
|
||||
(`requiredToolsUsed`, `stringIncludesAnyOf`) — not through exact returned row
|
||||
values. An empty/absent `datatables` seed makes `list_datatables` return `[]`,
|
||||
for a datatable that keeps its schema as migrations. Each one becomes a real datatable of
|
||||
the case's workspace, backed by its scratch database, so the datatable and SQL tools see
|
||||
exactly what a query would. An absent `datatables` seed leaves the workspace with none,
|
||||
which is what the "no datatable configured" blocking cases rely on.
|
||||
|
||||
Set `WMILL_AI_EVAL_DISABLE_ACTIVE_EDITOR_CONTEXT=1` to run those cases with
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
handleBenchmarkApiFetch,
|
||||
hasBenchmarkApiHandler,
|
||||
registerBenchmarkWorkspaceRunnables,
|
||||
unregisterBenchmarkWorkspace
|
||||
} from './mockBackend'
|
||||
|
||||
// A global eval run registers its workspace under a mkdtemp path, so the workspace id the
|
||||
// frontend interpolates into the models URL carries slashes. A handler that assumed a single
|
||||
// path segment silently fell through to the network, and every run took the offline fallback.
|
||||
const WORKSPACE = '/tmp/wmill-frontend-global-benchmark-abc123'
|
||||
const RESOURCE = 'f/evals/global/anthropic_main'
|
||||
const URL_FOR = (workspace: string) =>
|
||||
`http://benchmark.local/api/w/${workspace}/ai/proxy/models`
|
||||
|
||||
describe('benchmark /ai/proxy/models', () => {
|
||||
it('serves the seeded listing for a workspace id that is a path', async () => {
|
||||
registerBenchmarkWorkspaceRunnables(WORKSPACE, {
|
||||
aiProviders: [
|
||||
{ path: RESOURCE, kind: 'anthropic', models: ['claude-sonnet-5', 'claude-opus-5'] }
|
||||
]
|
||||
})
|
||||
try {
|
||||
expect(hasBenchmarkApiHandler(URL_FOR(WORKSPACE))).toBe(true)
|
||||
const response = handleBenchmarkApiFetch(URL_FOR(WORKSPACE), {
|
||||
headers: { 'X-Resource-Path': RESOURCE, 'X-Provider': 'anthropic' }
|
||||
})
|
||||
await expect(response.json()).resolves.toEqual({
|
||||
data: [{ id: 'claude-sonnet-5' }, { id: 'claude-opus-5' }]
|
||||
})
|
||||
} finally {
|
||||
unregisterBenchmarkWorkspace(WORKSPACE)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,95 @@
|
||||
// The pipeline editors a session chat opens with open_preview(kind="pipeline"). In production
|
||||
// PipelineEditorView mounts one per folder and registers its helpers once the canvas is up;
|
||||
// here the same state and helper factory run without a canvas, so build_pipeline_node and
|
||||
// edit_pipeline_node stage drafts exactly as they would in a session.
|
||||
import { AssetService } from "$lib/gen";
|
||||
import { DATA_ASSET_KINDS } from "../../../../../frontend/src/lib/components/assets/AssetGraph/cascadeRun";
|
||||
import { createPipelineAiHelpers } from "../../../../../frontend/src/lib/components/assets/AssetGraph/pipelineAiHelpers";
|
||||
import { PipelineEditorState } from "../../../../../frontend/src/lib/components/assets/AssetGraph/pipelineEditorState.svelte";
|
||||
import { resolveGraph } from "../../../../../frontend/src/lib/components/assets/AssetGraph/resolveGraph";
|
||||
import type { AssetGraphResponse } from "../../../../../frontend/src/lib/components/assets/AssetGraph/types";
|
||||
import type {
|
||||
PipelineAIChatHelpers,
|
||||
PipelineToolHelpers,
|
||||
} from "../../../../../frontend/src/lib/components/copilot/chat/pipeline/core";
|
||||
import { normalizePipelineFolder } from "../../../../../frontend/src/lib/utils/pipelineFolder";
|
||||
import type { GlobalDraft } from "../../../../core/validators";
|
||||
|
||||
interface Editor {
|
||||
state: PipelineEditorState;
|
||||
helpers: PipelineAIChatHelpers;
|
||||
}
|
||||
|
||||
export interface EvalPipelineEditors {
|
||||
/** Opens the folder's editor, as the session's pipeline preview tab mounts one. */
|
||||
open(folder: string): Promise<string>;
|
||||
folders(): string[];
|
||||
toolHelpers: PipelineToolHelpers;
|
||||
/** The nodes the editors staged, as the script drafts a deploy of the pipeline writes. */
|
||||
drafts(): GlobalDraft[];
|
||||
}
|
||||
|
||||
export function createEvalPipelineEditors(workspace: string): EvalPipelineEditors {
|
||||
const editors = new Map<string, Editor>();
|
||||
|
||||
async function open(folder: string): Promise<string> {
|
||||
const key = normalizePipelineFolder(folder);
|
||||
if (editors.has(key)) return key;
|
||||
const state = new PipelineEditorState();
|
||||
state.folder = key;
|
||||
const base = (await AssetService.getAssetsGraph({
|
||||
workspace,
|
||||
folder: key,
|
||||
assetKinds: DATA_ASSET_KINDS.join(","),
|
||||
})) as AssetGraphResponse;
|
||||
const helpers = createPipelineAiHelpers({
|
||||
getFolder: () => key,
|
||||
getWorkspace: () => workspace,
|
||||
getResolvedGraph: () =>
|
||||
resolveGraph({
|
||||
base,
|
||||
drafts: state.drafts,
|
||||
liveBodyAssets: state.liveBodyAssets,
|
||||
liveAnnotations: state.liveAnnotations,
|
||||
// Filled from deployed sources by the view's prefetch; a fixture deploys none.
|
||||
inferredWritesByPath: new Map(),
|
||||
inferredReadsByPath: new Map(),
|
||||
annotatedNativeKindsByPath: new Map(),
|
||||
triggerDrafts: state.triggerDrafts.values(),
|
||||
}),
|
||||
getDrafts: () => state.drafts,
|
||||
setDrafts: (next) => (state.drafts = next),
|
||||
newDraftLocalId: state.newDraftLocalId,
|
||||
hasTriggerDrafts: () => state.triggerDrafts.size > 0,
|
||||
getTriggerDrafts: () => state.triggerDrafts,
|
||||
setTriggerDraft: state.setTriggerDraft,
|
||||
onForgetPath: (path) => {
|
||||
state.forgetPath(path);
|
||||
state.discardTriggerDraftsFor(path);
|
||||
},
|
||||
});
|
||||
editors.set(key, { state, helpers });
|
||||
return key;
|
||||
}
|
||||
|
||||
return {
|
||||
open,
|
||||
folders: () => [...editors.keys()],
|
||||
toolHelpers: {
|
||||
pipelines: () => [...editors.values()].map((e) => e.helpers),
|
||||
pipelineFolders: () => [...editors.keys()],
|
||||
ensurePipeline: async (folder) => editors.get(normalizePipelineFolder(folder))?.helpers,
|
||||
},
|
||||
drafts: () =>
|
||||
[...editors.values()].flatMap((e) =>
|
||||
[...e.state.drafts.values()].map((d) => ({
|
||||
type: "script",
|
||||
path: d.script.path,
|
||||
language: d.script.language,
|
||||
summary: d.script.summary,
|
||||
value: d.script.content,
|
||||
isDraft: true,
|
||||
})),
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -42,6 +42,7 @@ export interface EvalPreviewTabFixture {
|
||||
// by session id: global cases run concurrently, so a per-run registration would have every
|
||||
// case answering out of whichever run registered last.
|
||||
const panels = new Map<string, SessionPreviewTabs>();
|
||||
const pipelineOpeners = new Map<string, (folder: string) => Promise<string>>();
|
||||
|
||||
const NO_SESSION = "No active session; the preview panel is unavailable.";
|
||||
|
||||
@@ -62,9 +63,15 @@ setOpenPreviewHandler(async ({ sessionId, kind, path }) => {
|
||||
if (!target) {
|
||||
return `Error: ${kind} targets cannot be shown in the preview panel.`;
|
||||
}
|
||||
// The pipeline branch of the production handler waits on an editor that only exists once
|
||||
// a canvas mounts, which never happens here — a pipeline preview reports as any other.
|
||||
const result = owner.open(target);
|
||||
const openPipeline = pipelineOpeners.get(sessionId!);
|
||||
if (kind === "pipeline" && openPipeline) {
|
||||
const folder = await openPipeline(path);
|
||||
// Production's success text (sessionRuntime.svelte.ts): it names the node path prefix.
|
||||
return `${
|
||||
result.status === "focused" ? "Focused the" : "Opened the"
|
||||
} pipeline editor for folder "${folder}" in the side panel. build_pipeline_node, edit_pipeline_node and the other pipeline tools are now in your tool list: call them in your next step. Its nodes go at paths under \`f/${folder}/\` (e.g. \`f/${folder}/<node_name>\`).`;
|
||||
}
|
||||
return result.status === "focused"
|
||||
? `A preview tab is already showing ${kind} "${path}" — focused it.`
|
||||
: `Opened ${kind} preview for ${path} in a new tab in the side panel.`;
|
||||
@@ -112,6 +119,8 @@ export function createEvalPreviewPanel(input: {
|
||||
tabs: EvalPreviewTabFixture[];
|
||||
/** Artifact ids by name, from the artifact fixture seeding. */
|
||||
artifactIds: Map<string, string>;
|
||||
/** Mounts the folder's pipeline editor and resolves to its normalized folder. */
|
||||
openPipeline: (folder: string) => Promise<string>;
|
||||
}): EvalPreviewPanel {
|
||||
// Nothing durable to write back to, and no debounce worth waiting on.
|
||||
const owner = new SessionPreviewTabs(
|
||||
@@ -129,6 +138,7 @@ export function createEvalPreviewPanel(input: {
|
||||
if (requestedActive) owner.select(requestedActive);
|
||||
// Registered last: seeding throws on a malformed fixture, and this map outlives the run.
|
||||
panels.set(input.sessionId, owner);
|
||||
pipelineOpeners.set(input.sessionId, input.openPipeline);
|
||||
|
||||
return {
|
||||
openArtifact: (id, name, version) => {
|
||||
@@ -143,6 +153,7 @@ export function createEvalPreviewPanel(input: {
|
||||
},
|
||||
dispose: () => {
|
||||
panels.delete(input.sessionId);
|
||||
pipelineOpeners.delete(input.sessionId);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
import { mkdtemp, rm } from "fs/promises";
|
||||
import { tmpdir } from "os";
|
||||
import { join } from "path";
|
||||
import type { ChatCompletionMessageParam } from "openai/resources/chat/completions.mjs";
|
||||
import type { AIProvider, OperatorSettings } from "$lib/gen/types.gen";
|
||||
import {
|
||||
@@ -28,7 +25,10 @@ import { resolveResourceTypeSync } from "../../../../../frontend/src/lib/compone
|
||||
import { appendPlanModeInstructions } from "../../../../../frontend/src/lib/components/copilot/chat/planMode";
|
||||
import type { Tool as ProductionTool } from "../../../../../frontend/src/lib/components/copilot/chat/shared";
|
||||
import { createEvalPlanTools } from "./planModeTools";
|
||||
import { createEvalPipelineEditors } from "./evalPipelineEditors";
|
||||
import { pipelineTools } from "../../../../../frontend/src/lib/components/copilot/chat/pipeline/core";
|
||||
import { UserDraft } from "../../../../../frontend/src/lib/userDraft.svelte";
|
||||
import { DraftService } from "$lib/gen";
|
||||
import {
|
||||
createEvalArtifactHelpers,
|
||||
type SeededArtifact,
|
||||
@@ -38,15 +38,19 @@ import {
|
||||
type EvalPreviewPanel,
|
||||
type EvalPreviewTabFixture,
|
||||
} from "./evalPreviewTabs";
|
||||
import type { EvalCaseProfile, ModeRunContext } from "../../../../core/types";
|
||||
import type {
|
||||
EvalCaseProfile,
|
||||
ModeRunContext,
|
||||
PipelineRunSpec,
|
||||
} from "../../../../core/types";
|
||||
import type { GlobalDraftState } from "../../../../core/validators";
|
||||
import type { WindmillBackendSettings } from "../../../../core/windmillBackendSettings";
|
||||
import {
|
||||
registerBenchmarkWorkspaceRunnables,
|
||||
seedBenchmarkDraft,
|
||||
registerBenchmarkAiModels,
|
||||
unregisterBenchmarkWorkspaceRunnables,
|
||||
type BenchmarkWorkspaceRunnables,
|
||||
} from "../../mockBackend";
|
||||
import { createRealWorkspace } from "./realWorkspace";
|
||||
import { runEval } from "../shared";
|
||||
import type { TokenUsage, ToolCallDetail } from "../shared/types";
|
||||
|
||||
@@ -135,12 +139,13 @@ export interface GlobalEvalOptions {
|
||||
planMode?: boolean;
|
||||
// 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`).
|
||||
pipelineRun?: PipelineRunSpec;
|
||||
model?: string;
|
||||
maxIterations?: number;
|
||||
userAnswers?: string[];
|
||||
provider?: AIProvider;
|
||||
backend: WindmillBackendSettings;
|
||||
workspaceRoot?: string;
|
||||
// Artifacts the session already holds when the run starts.
|
||||
artifacts?: SeededArtifact[];
|
||||
/** Tabs already open in the side panel, including any artifact version the reader pinned. */
|
||||
@@ -153,18 +158,22 @@ export async function runGlobalEval(
|
||||
apiKey: string,
|
||||
options: GlobalEvalOptions,
|
||||
): Promise<GlobalEvalResult> {
|
||||
const workspaceRoot =
|
||||
options.workspaceRoot ??
|
||||
(await mkdtemp(join(tmpdir(), "wmill-frontend-global-benchmark-")));
|
||||
const realWorkspace = await createRealWorkspace({
|
||||
settings: options.backend,
|
||||
caseId: options.runContext?.caseId ?? "global",
|
||||
attempt: options.runContext?.attempt ?? 1,
|
||||
fixtures: options.workspaceFixtures ?? {},
|
||||
user: options.user,
|
||||
profile: options.profile,
|
||||
});
|
||||
const workspaceRoot = realWorkspace.id;
|
||||
|
||||
clearGlobalDrafts(workspaceRoot);
|
||||
registerBenchmarkWorkspaceRunnables(
|
||||
registerBenchmarkAiModels(
|
||||
workspaceRoot,
|
||||
options.workspaceFixtures ?? {},
|
||||
options.workspaceFixtures?.aiProviders ?? [],
|
||||
);
|
||||
seedLiveEditorDrafts(workspaceRoot, options.liveEditorDrafts ?? []);
|
||||
// No deploy rules in the mock workspace, so they always pass. The role is read as a server
|
||||
// that predates workspace roles describes it, from `operator_settings`.
|
||||
// The eval workspace has no deploy rules, so they always pass.
|
||||
const roleAccess =
|
||||
options.profile &&
|
||||
capabilitiesForRole({
|
||||
@@ -187,6 +196,7 @@ export async function runGlobalEval(
|
||||
let panel: EvalPreviewPanel | undefined;
|
||||
|
||||
try {
|
||||
await seedLiveEditorDrafts(workspaceRoot, options.liveEditorDrafts ?? []);
|
||||
const evalArtifacts = createEvalArtifactHelpers(options.artifacts);
|
||||
// Only a session chat has a side panel, so only it gets one here. Seeded tabs would
|
||||
// otherwise vanish without a word, and the case would measure an empty panel.
|
||||
@@ -201,11 +211,15 @@ export async function runGlobalEval(
|
||||
"This case sets runtime.profile, which only a session chat applies — set runtime.sessionChat: true on the case.",
|
||||
);
|
||||
}
|
||||
const pipelineEditors = options.sessionChat
|
||||
? createEvalPipelineEditors(workspaceRoot)
|
||||
: undefined;
|
||||
if (options.sessionChat) {
|
||||
panel = createEvalPreviewPanel({
|
||||
sessionId: evalArtifacts.sessionId,
|
||||
tabs: options.previewTabs ?? [],
|
||||
artifactIds: evalArtifacts.seededIds,
|
||||
openPipeline: pipelineEditors!.open,
|
||||
});
|
||||
}
|
||||
const model = options.model ?? "claude-haiku-4-5-20251001";
|
||||
@@ -220,33 +234,47 @@ export async function runGlobalEval(
|
||||
: undefined;
|
||||
// Pass the seeded identity straight to the prompt builder rather than mutating
|
||||
// the process-global `userStore`, so concurrent cases never race on it.
|
||||
const baseSystemMessage = assembleGlobalSystemMessage(undefined, {
|
||||
user: options.user,
|
||||
previewTools: options.sessionChat ?? false,
|
||||
access,
|
||||
...(heldInUse && {
|
||||
sessionContext: { workspaceId: workspaceRoot, useMode: "role" as const },
|
||||
}),
|
||||
});
|
||||
// Production adds the pipeline section and tools once a pipeline editor is open.
|
||||
const assembleSystemMessage = () =>
|
||||
assembleGlobalSystemMessage(undefined, {
|
||||
user: options.user,
|
||||
previewTools: options.sessionChat ?? false,
|
||||
access,
|
||||
...(heldInUse && {
|
||||
sessionContext: { workspaceId: workspaceRoot, useMode: "role" as const },
|
||||
}),
|
||||
pipelineFolders: pipelineEditors?.folders(),
|
||||
});
|
||||
const baseSystemMessage = assembleSystemMessage();
|
||||
const helpers = {
|
||||
...evalArtifacts.helpers,
|
||||
// A standalone chat has no session: the tools that behave differently in one (a pipeline
|
||||
// node is built into the pipeline draft there, not written as a script) read this.
|
||||
sessionId: options.sessionChat ? evalArtifacts.helpers.sessionId : undefined,
|
||||
access,
|
||||
...(panel && { openArtifact: panel.openArtifact }),
|
||||
...pipelineEditors?.toolHelpers,
|
||||
};
|
||||
const pipelineToolNames = new Set(pipelineTools.map((t) => t.def.function.name));
|
||||
const rawResult = await runEval({
|
||||
userPrompt,
|
||||
systemMessage: baseSystemMessage,
|
||||
// Re-derived per request, as production's getter is: the instructions have to leave
|
||||
// the prompt when the plan is approved, or the model is still told it may not build
|
||||
// while the gate has already opened.
|
||||
getSystemMessage: planMode
|
||||
? () =>
|
||||
planMode.isPlanModeActive()
|
||||
? appendPlanModeInstructions(baseSystemMessage, 0)
|
||||
: baseSystemMessage
|
||||
: undefined,
|
||||
getSystemMessage:
|
||||
planMode || pipelineEditors
|
||||
? () => {
|
||||
const message = assembleSystemMessage();
|
||||
return planMode?.isPlanModeActive()
|
||||
? appendPlanModeInstructions(message, 0)
|
||||
: message;
|
||||
}
|
||||
: undefined,
|
||||
isPlanModeActive: planMode?.isPlanModeActive,
|
||||
isToolAvailable: planMode?.isToolAvailable,
|
||||
isToolAvailable: (name) =>
|
||||
(!pipelineToolNames.has(name) || (pipelineEditors?.folders().length ?? 0) > 0) &&
|
||||
(planMode?.isToolAvailable?.(name) ?? true),
|
||||
userMessage: prepareGlobalUserMessage(userPrompt, [], {
|
||||
...(injectActiveEditorContext ? { workspace: workspaceRoot } : {}),
|
||||
activePreview: panel?.activePreview(),
|
||||
@@ -257,14 +285,20 @@ export async function runGlobalEval(
|
||||
getGlobalEvalTools(options.sessionChat ?? false),
|
||||
access,
|
||||
),
|
||||
...(pipelineEditors
|
||||
? filterSessionTools(pipelineTools as ProductionTool<{}>[], access)
|
||||
: []),
|
||||
...(planMode?.tools ?? []),
|
||||
],
|
||||
helpers,
|
||||
apiKey,
|
||||
getOutput: async () => ({
|
||||
...(await collectGlobalDraftState(workspaceRoot)),
|
||||
artifacts: evalArtifacts.snapshot(),
|
||||
}),
|
||||
getOutput: async () => {
|
||||
const state = await collectGlobalDraftState(workspaceRoot);
|
||||
return {
|
||||
drafts: [...state.drafts, ...(pipelineEditors?.drafts() ?? [])],
|
||||
artifacts: evalArtifacts.snapshot(),
|
||||
};
|
||||
},
|
||||
onAssistantMessageStart: options.runContext?.onAssistantMessageStart,
|
||||
onAssistantToken: options.runContext?.onAssistantChunk,
|
||||
onAssistantMessageEnd: options.runContext?.onAssistantMessageEnd,
|
||||
@@ -275,14 +309,27 @@ export async function runGlobalEval(
|
||||
model,
|
||||
workspace: workspaceRoot,
|
||||
provider: options.provider,
|
||||
backend: options.backend,
|
||||
backend: realWorkspace.backend,
|
||||
caseId: options.runContext?.caseId,
|
||||
attempt: options.runContext?.attempt,
|
||||
},
|
||||
});
|
||||
|
||||
const state: GlobalDraftState = options.pipelineRun
|
||||
? {
|
||||
...rawResult.output,
|
||||
pipelineRun: await realWorkspace.runPipeline(
|
||||
options.pipelineRun,
|
||||
rawResult.output.drafts,
|
||||
),
|
||||
}
|
||||
: rawResult.output;
|
||||
if (state.pipelineRun?.skipped) {
|
||||
console.warn(`[ai_evals] pipeline run skipped: ${state.pipelineRun.skipped}`);
|
||||
}
|
||||
|
||||
return {
|
||||
state: rawResult.output,
|
||||
state,
|
||||
success: rawResult.success,
|
||||
error: rawResult.error,
|
||||
assistantMessageCount: rawResult.iterations,
|
||||
@@ -299,9 +346,7 @@ export async function runGlobalEval(
|
||||
clearLiveEditorDrafts(workspaceRoot, options.liveEditorDrafts ?? []);
|
||||
seedOperatorSettings(workspaceRoot, undefined);
|
||||
unregisterBenchmarkWorkspaceRunnables(workspaceRoot);
|
||||
if (!options.workspaceRoot) {
|
||||
await rm(workspaceRoot, { recursive: true, force: true });
|
||||
}
|
||||
await realWorkspace.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -331,17 +376,22 @@ async function collectGlobalDraftState(
|
||||
return { drafts: drafts as GlobalDraftState["drafts"] };
|
||||
}
|
||||
|
||||
function seedLiveEditorDrafts(
|
||||
async function seedLiveEditorDrafts(
|
||||
workspace: string,
|
||||
fixtures: GlobalLiveEditorDraftFixture[],
|
||||
): void {
|
||||
): Promise<void> {
|
||||
for (const fixture of fixtures) {
|
||||
const itemKind = LIVE_EDITOR_ITEM_KINDS[fixture.type];
|
||||
const storagePath = fixture.storagePath ?? fixture.effectivePath ?? "";
|
||||
if (fixture.value !== undefined) {
|
||||
// Seed as a backend draft row, not an in-tab cell: a cell would shadow the
|
||||
// model's DB-backed edit when the output is read back via listGlobalDrafts.
|
||||
seedBenchmarkDraft(workspace, itemKind, storagePath, fixture.value);
|
||||
await DraftService.updateDraft({
|
||||
workspace,
|
||||
kind: itemKind,
|
||||
path: storagePath,
|
||||
requestBody: { value: fixture.value, force: true },
|
||||
});
|
||||
}
|
||||
UserDraft.setLiveEditorDraft({
|
||||
workspace,
|
||||
@@ -382,6 +432,10 @@ function seedOperatorSettings(
|
||||
username: "",
|
||||
color: "",
|
||||
operator_settings: operatorSettings as OperatorSettings,
|
||||
role: "operator",
|
||||
capabilities: legacyOperatorCapabilities(
|
||||
operatorSettings as OperatorSettings,
|
||||
),
|
||||
is_dev_workspace: false,
|
||||
disabled: false,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { rootNodes } from "./pipelineRun";
|
||||
|
||||
describe("rootNodes", () => {
|
||||
const paths = ["f/shop/ingest", "f/shop/daily"];
|
||||
const edges = [
|
||||
{ runnable_path: "f/shop/ingest", asset_kind: "ducklake", asset_path: "main/orders", access_type: "w" as const },
|
||||
{ runnable_path: "f/shop/daily", asset_kind: "ducklake", asset_path: "main/orders", access_type: "r" as const },
|
||||
];
|
||||
|
||||
it("does not run a node that reads an upstream table directly, whatever it triggers on", () => {
|
||||
const triggers = [
|
||||
{ trigger_kind: "asset", asset_kind: "ducklake", asset_path: "main/order", runnable_path: "f/shop/daily" },
|
||||
];
|
||||
expect(rootNodes(paths, triggers, edges)).toEqual(["f/shop/ingest"]);
|
||||
});
|
||||
|
||||
it("keeps a node that reads its own materialized table a root", () => {
|
||||
const selfRead = [
|
||||
{ runnable_path: "f/shop/ingest", asset_kind: "ducklake", asset_path: "main/orders", access_type: "rw" as const },
|
||||
];
|
||||
expect(rootNodes(["f/shop/ingest"], [], selfRead)).toEqual(["f/shop/ingest"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,241 @@
|
||||
// Runs the pipeline a case built, on the case's own workspace, once the chat is over: its nodes
|
||||
// are deployed, the nodes nothing upstream feeds are run, and the server's asset triggers run
|
||||
// the rest. What a case then asserts is the data the pipeline produced, not how its source reads.
|
||||
import type { GlobalDraft } from "../../../../core/validators";
|
||||
import type {
|
||||
PipelineRunQuery,
|
||||
PipelineRunResult,
|
||||
PipelineRunSpec,
|
||||
} from "../../../../core/types";
|
||||
|
||||
export type Api = (method: string, path: string, body?: unknown) => Promise<any>;
|
||||
|
||||
const DEFAULT_TIMEOUT_SECONDS = 300;
|
||||
/** Past `LISTEN_NEW_EVENTS_INTERVAL_SEC` (10 s by default). */
|
||||
const PRODUCER_CACHE_EVICTION_MS = 12_000;
|
||||
/** Deployments and the cascade are over once no job of the folder has been queued or running
|
||||
* for this long. */
|
||||
const QUIET_MS = 5_000;
|
||||
|
||||
interface GraphTrigger {
|
||||
trigger_kind: string;
|
||||
asset_kind?: string;
|
||||
asset_path?: string;
|
||||
runnable_path: string;
|
||||
}
|
||||
|
||||
interface GraphEdge {
|
||||
runnable_path: string;
|
||||
asset_kind: string;
|
||||
asset_path: string;
|
||||
access_type: "r" | "w" | "rw" | null;
|
||||
}
|
||||
|
||||
export async function runPipeline(
|
||||
api: Api,
|
||||
spec: PipelineRunSpec,
|
||||
drafts: GlobalDraft[],
|
||||
/** Points every DuckLake at an empty catalog. The model's test runs fill the lake it worked
|
||||
* on, and a materialize that rewrites a table unchanged triggers nothing downstream. */
|
||||
emptyLakes: () => Promise<void>,
|
||||
): Promise<PipelineRunResult> {
|
||||
const prefix = `f/${spec.folder}/`;
|
||||
const nodes = drafts.filter(
|
||||
(d) =>
|
||||
d.type === "script" &&
|
||||
d.path.startsWith(prefix) &&
|
||||
typeof d.value === "string" &&
|
||||
isPipelineNode(d.value),
|
||||
);
|
||||
const result: PipelineRunResult = { nodes: [], queries: [] };
|
||||
if (nodes.length === 0) {
|
||||
result.error = `no pipeline node was drafted under ${prefix}`;
|
||||
return result;
|
||||
}
|
||||
const deadline = Date.now() + (spec.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS) * 1000;
|
||||
|
||||
for (const node of nodes) {
|
||||
try {
|
||||
await api("POST", "scripts/create", {
|
||||
path: node.path,
|
||||
summary: node.summary ?? "",
|
||||
description: "",
|
||||
content: node.value,
|
||||
language: node.language ?? "duckdb",
|
||||
});
|
||||
} catch (error) {
|
||||
result.nodes.push({ path: node.path, deployError: String(error) });
|
||||
}
|
||||
}
|
||||
const deployed = nodes
|
||||
.map((n) => n.path)
|
||||
.filter((p) => !result.nodes.some((r) => r.path === p));
|
||||
// A failure past this point is the pipeline's outcome, not the harness's: it is recorded so
|
||||
// the case keeps its drafts and judge.
|
||||
try {
|
||||
await runFromRoots(api, spec, deployed, deadline, emptyLakes, result);
|
||||
} catch (error) {
|
||||
result.error = String(error);
|
||||
}
|
||||
for (const query of spec.queries ?? []) {
|
||||
result.queries.push(await runQuery(api, query));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function runFromRoots(
|
||||
api: Api,
|
||||
spec: PipelineRunSpec,
|
||||
deployed: string[],
|
||||
deadline: number,
|
||||
emptyLakes: () => Promise<void>,
|
||||
result: PipelineRunResult,
|
||||
): Promise<void> {
|
||||
const prefix = `f/${spec.folder}/`;
|
||||
// A node's asset triggers are recorded when its deployment job completes, not at create.
|
||||
await waitForQuietQueue(api, spec.folder, deadline);
|
||||
// Dispatch reads a per-process cache of which scripts produce what, which the model's test
|
||||
// runs have filled; a deploy evicts it only at each process's next notify-event poll.
|
||||
await new Promise((resolve) => setTimeout(resolve, PRODUCER_CACHE_EVICTION_MS));
|
||||
|
||||
const graph = await api("GET", `assets/graph?folder=${encodeURIComponent(spec.folder)}`);
|
||||
const roots = rootNodes(
|
||||
deployed,
|
||||
(graph.triggers ?? []) as GraphTrigger[],
|
||||
(graph.edges ?? []) as GraphEdge[],
|
||||
);
|
||||
result.roots = roots;
|
||||
await emptyLakes();
|
||||
const startedAt = new Date(Date.now() - 1_000).toISOString();
|
||||
for (const path of roots) {
|
||||
await api("POST", `jobs/run/p/${path}`, {});
|
||||
}
|
||||
await waitForQuietQueue(api, spec.folder, deadline).catch((error) => {
|
||||
result.error = String(error);
|
||||
});
|
||||
|
||||
const jobs: Array<{
|
||||
script_path?: string;
|
||||
success?: boolean;
|
||||
type?: string;
|
||||
created_by?: string;
|
||||
id: string;
|
||||
}> = await api(
|
||||
"GET",
|
||||
// Deployed runs of this run only: the model's own test runs are previews.
|
||||
`jobs/list?script_path_start=${encodeURIComponent(prefix)}&job_kinds=script` +
|
||||
`&created_after=${encodeURIComponent(startedAt)}&per_page=100`,
|
||||
);
|
||||
for (const path of deployed) {
|
||||
// Newest first: the last run of the node is what its table holds.
|
||||
const run = jobs.find((j) => j.script_path === path && j.type === "CompletedJob");
|
||||
const entry: PipelineRunResult["nodes"][number] = { path, ran: !!run };
|
||||
if (run) {
|
||||
entry.success = run.success === true;
|
||||
entry.triggeredBy = run.created_by;
|
||||
if (!entry.success) {
|
||||
const failed = await api("GET", `jobs_u/completed/get_result/${run.id}`).catch(
|
||||
(error) => ({ error: String(error) }),
|
||||
);
|
||||
entry.error = summarize(failed);
|
||||
}
|
||||
}
|
||||
result.nodes.push(entry);
|
||||
}
|
||||
}
|
||||
|
||||
function isPipelineNode(content: string): boolean {
|
||||
return /^\s*(--|\/\/|#)\s*pipeline\b/m.test(content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Nodes no other node of the pipeline feeds: none of the assets they read or trigger on is
|
||||
* written by another node. Reads count too, so a node that reads an upstream table but
|
||||
* triggers on the wrong asset is never run directly, and fails as never having run.
|
||||
*/
|
||||
export function rootNodes(
|
||||
paths: string[],
|
||||
triggers: GraphTrigger[],
|
||||
edges: GraphEdge[],
|
||||
): string[] {
|
||||
const inPipeline = new Set(paths);
|
||||
const writers = new Map<string, Set<string>>();
|
||||
for (const e of edges) {
|
||||
if (inPipeline.has(e.runnable_path) && (e.access_type === "w" || e.access_type === "rw")) {
|
||||
const key = `${e.asset_kind}:${e.asset_path}`;
|
||||
writers.set(key, (writers.get(key) ?? new Set()).add(e.runnable_path));
|
||||
}
|
||||
}
|
||||
const fedByAnother = (path: string, kind: string | undefined, assetPath: string | undefined) =>
|
||||
[...(writers.get(`${kind}:${assetPath}`) ?? [])].some((writer) => writer !== path);
|
||||
return paths.filter(
|
||||
(path) =>
|
||||
!triggers.some(
|
||||
(t) =>
|
||||
t.trigger_kind === "asset" &&
|
||||
t.runnable_path === path &&
|
||||
fedByAnother(path, t.asset_kind, t.asset_path),
|
||||
) &&
|
||||
!edges.some(
|
||||
(e) =>
|
||||
e.runnable_path === path &&
|
||||
(e.access_type === "r" || e.access_type === "rw") &&
|
||||
fedByAnother(path, e.asset_kind, e.asset_path),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForQuietQueue(api: Api, folder: string, deadline: number): Promise<void> {
|
||||
let quietSince: number | undefined;
|
||||
await waitUntil(deadline, `the jobs of f/${folder} to finish`, async () => {
|
||||
const active: unknown[] = await api(
|
||||
"GET",
|
||||
`jobs/queue/list?script_path_start=${encodeURIComponent(`f/${folder}/`)}&per_page=10`,
|
||||
);
|
||||
if (active.length > 0) {
|
||||
quietSince = undefined;
|
||||
return false;
|
||||
}
|
||||
quietSince ??= Date.now();
|
||||
return Date.now() - quietSince >= QUIET_MS;
|
||||
});
|
||||
}
|
||||
|
||||
async function runQuery(api: Api, query: PipelineRunQuery) {
|
||||
const lake = query.ducklake ?? "main";
|
||||
const content = `ATTACH 'ducklake://${lake}' AS dl;\n${query.sql}`;
|
||||
const result = await api("POST", "jobs/run_wait_result/preview", {
|
||||
content,
|
||||
language: "duckdb",
|
||||
args: {},
|
||||
}).catch((error) => ({ error: String(error) }));
|
||||
if (result && typeof result === "object" && !Array.isArray(result) && "error" in result) {
|
||||
return { name: query.name, error: summarize(result) };
|
||||
}
|
||||
return { name: query.name, rows: Array.isArray(result) ? result : [result] };
|
||||
}
|
||||
|
||||
function summarize(value: unknown): string {
|
||||
const error =
|
||||
value && typeof value === "object" && "error" in value
|
||||
? (value as { error: unknown }).error
|
||||
: value;
|
||||
const text =
|
||||
error && typeof error === "object" && "message" in error
|
||||
? String((error as { message: unknown }).message)
|
||||
: typeof error === "string"
|
||||
? error
|
||||
: JSON.stringify(error);
|
||||
return text.length > 600 ? `${text.slice(0, 600)}…` : text;
|
||||
}
|
||||
|
||||
async function waitUntil(
|
||||
deadline: number,
|
||||
what: string,
|
||||
done: () => Promise<boolean>,
|
||||
): Promise<void> {
|
||||
while (!(await done())) {
|
||||
if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`);
|
||||
await new Promise((resolve) => setTimeout(resolve, 1_000));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,786 @@
|
||||
// A real Windmill workspace per global-mode attempt. The session's tools run on the backend
|
||||
// (`/api/w/<ws>/ai_session_tools/<name>`), so a case's fixture has to exist there: this creates
|
||||
// the workspace, seeds it through the public API, and deletes it afterwards.
|
||||
import { execFile } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { promisify } from "node:util";
|
||||
import type { WindmillBackendSettings } from "../../../../core/windmillBackendSettings";
|
||||
import type { EvalCaseProfile } from "../../../../core/types";
|
||||
import {
|
||||
syncedResourceTypes,
|
||||
type BenchmarkDatatableSeed,
|
||||
type BenchmarkWorkspaceRunnables,
|
||||
} from "../../mockBackend";
|
||||
import { WindmillBackendClient } from "../../windmillBackend";
|
||||
import { buildWorkspaceId } from "../../workspaceId";
|
||||
import type { GlobalUserFixture } from "./globalEvalRunner";
|
||||
import { runPipeline, type Api } from "./pipelineRun";
|
||||
import type { GlobalDraft } from "../../../../core/validators";
|
||||
import type { PipelineRunResult, PipelineRunSpec } from "../../../../core/types";
|
||||
|
||||
/** Workspace id -> the token its case runs as. Read by the adapter's fetch stub. */
|
||||
const activeWorkspaces = new Map<string, string>();
|
||||
let adminToken: string | undefined;
|
||||
let baseUrl: string | undefined;
|
||||
|
||||
export function realWorkspaceRoute(
|
||||
url: string,
|
||||
): { url: string; token: string } | undefined {
|
||||
if (!baseUrl || !adminToken || !url.startsWith("/api/")) return undefined;
|
||||
const workspace = /^\/api\/w\/([^/?]+)/.exec(url)?.[1];
|
||||
const token = workspace
|
||||
? activeWorkspaces.get(decodeURIComponent(workspace))
|
||||
: activeWorkspaces.size > 0
|
||||
? adminToken
|
||||
: undefined;
|
||||
return token ? { url: `${baseUrl}${url}`, token } : undefined;
|
||||
}
|
||||
|
||||
// Without the `postgresql` tag (a `native` worker group) datatable fixtures and SQL tools hang.
|
||||
const DATATABLE_PG_URL =
|
||||
process.env.WMILL_AI_EVAL_DATATABLE_PG_URL ??
|
||||
"postgres://postgres:changeme@localhost:5432/postgres";
|
||||
const ROOT_PG_RESOURCE = "$res:u/admin/ai_evals_pg_root";
|
||||
const RESOURCE_TYPE_INDEX_WAIT_MS = 120_000;
|
||||
const WORKSPACE_SLOT_WAIT_MS = 30 * 60_000;
|
||||
/** The eval backend's own database, where a fixture user that is not the admin is created. */
|
||||
const DATABASE_URL = process.env.WMILL_AI_EVAL_DATABASE_URL;
|
||||
/** An S3-compatible store the eval backend reaches, for fixtures with `objectStorage`. */
|
||||
const S3_ENDPOINT = process.env.WMILL_AI_EVAL_S3_ENDPOINT;
|
||||
|
||||
export interface RealWorkspace {
|
||||
id: string;
|
||||
/** Settings that make the model proxy reuse this workspace instead of creating another. */
|
||||
backend: WindmillBackendSettings;
|
||||
/** Deploys and runs the pipeline the case drafted; see `validate.pipelineRun`. */
|
||||
runPipeline(spec: PipelineRunSpec, drafts: GlobalDraft[]): Promise<PipelineRunResult>;
|
||||
dispose(): Promise<void>;
|
||||
}
|
||||
|
||||
export async function createRealWorkspace(input: {
|
||||
settings: WindmillBackendSettings;
|
||||
caseId: string;
|
||||
attempt: number;
|
||||
fixtures: BenchmarkWorkspaceRunnables;
|
||||
user?: GlobalUserFixture;
|
||||
profile?: EvalCaseProfile;
|
||||
}): Promise<RealWorkspace> {
|
||||
// Job ids are unique across the instance, and a case prompt can name a fixture job by its
|
||||
// id: attempts that seed the same ids take turns, each holding them until it is deleted.
|
||||
const releaseJobIds = await holdJobIds(
|
||||
(input.fixtures.jobs ?? []).flatMap((job) => (job.id ? [job.id] : [])),
|
||||
);
|
||||
const client = new WindmillBackendClient(input.settings);
|
||||
baseUrl = input.settings.baseUrl;
|
||||
const id = buildWorkspaceId(input.caseId, input.attempt);
|
||||
const api = apiFor(client, id);
|
||||
try {
|
||||
adminToken = await client.getToken();
|
||||
await createWorkspace(api, id);
|
||||
} catch (error) {
|
||||
releaseJobIds();
|
||||
throw error;
|
||||
}
|
||||
const scratchDbs: string[] = [];
|
||||
let userToken: string | undefined;
|
||||
const dispose = async () => {
|
||||
activeWorkspaces.delete(id);
|
||||
if (input.user && DATABASE_URL) {
|
||||
await psql(`DELETE FROM token WHERE label = ${literal(tokenLabel(id))}`).catch(
|
||||
() => undefined,
|
||||
);
|
||||
}
|
||||
const workers = (input.fixtures.workers ?? []).map((w) => literal(w.worker));
|
||||
if (workers.length) {
|
||||
await psql(`DELETE FROM worker_ping WHERE worker IN (${workers.join(", ")})`).catch(
|
||||
() => undefined,
|
||||
);
|
||||
}
|
||||
for (const database of scratchDbs) {
|
||||
await sql(
|
||||
api,
|
||||
ROOT_PG_RESOURCE,
|
||||
`DROP DATABASE IF EXISTS "${database}" WITH (FORCE)`,
|
||||
).catch(() => undefined);
|
||||
}
|
||||
await api("DELETE", `/workspaces/delete/${id}`).catch(() => undefined);
|
||||
releaseJobIds();
|
||||
};
|
||||
try {
|
||||
activeWorkspaces.set(id, adminToken);
|
||||
userToken = await seedUser(api, id, input.user, input.profile);
|
||||
const storage = await seed(api, id, input.fixtures, scratchDbs);
|
||||
activeWorkspaces.set(id, userToken ?? adminToken);
|
||||
return {
|
||||
id,
|
||||
backend: { ...input.settings, workspaceOverride: id },
|
||||
runPipeline: async (spec, drafts) =>
|
||||
storage === "runnable"
|
||||
? runPipeline(api, spec, drafts, () =>
|
||||
configureLakes(api, id, input.fixtures.ducklakes ?? [], scratchDbs, "run"),
|
||||
)
|
||||
: {
|
||||
skipped:
|
||||
storage === "unconfigured"
|
||||
? "WMILL_AI_EVAL_S3_ENDPOINT is not set, so the workspace has no object storage to run the pipeline on"
|
||||
: "the fixture seeds no objectStorage",
|
||||
nodes: [],
|
||||
queries: [],
|
||||
},
|
||||
dispose,
|
||||
};
|
||||
} catch (error) {
|
||||
await dispose();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** Job id -> the turn of the last attempt that asked for it. */
|
||||
const jobIdTurns = new Map<string, Promise<void>>();
|
||||
|
||||
async function holdJobIds(ids: string[]): Promise<() => void> {
|
||||
let release!: () => void;
|
||||
const turn = new Promise<void>((resolve) => (release = resolve));
|
||||
const previous = ids.map((id) => jobIdTurns.get(id) ?? Promise.resolve());
|
||||
for (const id of ids) jobIdTurns.set(id, turn);
|
||||
await Promise.all(previous);
|
||||
return release;
|
||||
}
|
||||
|
||||
function apiFor(client: WindmillBackendClient, workspace: string): Api {
|
||||
return async (method, path, body) => {
|
||||
const scoped = path.startsWith("/") ? path : `/w/${workspace}/${path}`;
|
||||
const response = await client.request(scoped, {
|
||||
method,
|
||||
...(body instanceof FormData || body instanceof Blob
|
||||
? { body }
|
||||
: body === undefined
|
||||
? {}
|
||||
: {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
});
|
||||
const text = await response.text();
|
||||
if (!response.ok) {
|
||||
throw new Error(`${method} ${scoped}: ${response.status} ${text}`);
|
||||
}
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
return text;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// CE caps the number of workspaces, so a run with more concurrent attempts than slots waits.
|
||||
async function createWorkspace(api: Api, id: string): Promise<void> {
|
||||
const deadline = Date.now() + WORKSPACE_SLOT_WAIT_MS;
|
||||
for (;;) {
|
||||
try {
|
||||
await api("POST", "/workspaces/create", { id, name: id });
|
||||
return;
|
||||
} catch (error) {
|
||||
if (
|
||||
!String(error).includes("maximum number of workspaces") ||
|
||||
Date.now() > deadline
|
||||
) {
|
||||
throw error;
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 5_000));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The admin running the eval is `admin` in every workspace it creates. Any other identity is a
|
||||
// real member, so the backend enforces its rights as it would for that user; CE cannot create
|
||||
// users, so there the case runs as the admin, with the prompt alone describing the fixture user.
|
||||
async function seedUser(
|
||||
api: Api,
|
||||
workspace: string,
|
||||
user: GlobalUserFixture | undefined,
|
||||
profile: EvalCaseProfile | undefined,
|
||||
): Promise<string | undefined> {
|
||||
const username = user?.username ?? "admin";
|
||||
const writable = new Set(user?.folders ?? []);
|
||||
const readable = new Set([...(user?.folders_read ?? []), ...writable]);
|
||||
const asAdmin = username === "admin" && (user?.is_admin ?? true);
|
||||
let token: string | undefined;
|
||||
if (!asAdmin) {
|
||||
// CE cannot create users through the API, so the user and a token of theirs are written
|
||||
// straight into the instance database, as the backend's own tests do. The workspace
|
||||
// membership still goes through the API.
|
||||
const email = `${username}@ai-evals.windmill.dev`;
|
||||
token = `aievals${randomUUID().replace(/-/g, "")}`;
|
||||
await psql(
|
||||
`INSERT INTO password (email, password_hash, login_type, super_admin, verified, name, username)
|
||||
VALUES (${literal(email)}, 'ai-evals-no-login', 'password', false, true, ${literal(username)},
|
||||
${literal(username)})
|
||||
ON CONFLICT (email) DO UPDATE SET username = EXCLUDED.username;
|
||||
INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin)
|
||||
VALUES (encode(sha256(${literal(token)}::bytea), 'hex'), ${literal(token.slice(0, 10))},
|
||||
${literal(token)}, ${literal(email)}, ${literal(tokenLabel(workspace))}, false);`,
|
||||
);
|
||||
await api("POST", "workspaces/add_user", {
|
||||
email,
|
||||
is_admin: user?.is_admin ?? false,
|
||||
operator: profile?.operator ?? false,
|
||||
});
|
||||
}
|
||||
if (profile?.operator && profile.operatorSettings) {
|
||||
await api("POST", "workspaces/operator_settings", profile.operatorSettings);
|
||||
}
|
||||
for (const folder of readable) {
|
||||
await api("POST", "folders/create", {
|
||||
name: folder,
|
||||
...(asAdmin ? {} : { extra_perms: { [`u/${username}`]: writable.has(folder) } }),
|
||||
});
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
/** Seeds every fixture kind, recording the scratch databases it creates; returns whether a
|
||||
* pipeline can run on the workspace's storage. */
|
||||
async function seed(
|
||||
api: Api,
|
||||
workspace: string,
|
||||
fixtures: BenchmarkWorkspaceRunnables,
|
||||
scratchDbs: string[],
|
||||
): Promise<"runnable" | "unconfigured" | "none"> {
|
||||
// A fixture that sets no `resourceTypes` stands for an instance synced with the hub,
|
||||
// which an eval backend usually is not; the types the instance already holds stay its own.
|
||||
const held = new Set<string>(await api("GET", "resources/type/listnames"));
|
||||
const resourceTypes = (fixtures.resourceTypes ?? syncedResourceTypes()).filter(
|
||||
(rt) => !held.has(rt.name),
|
||||
);
|
||||
for (const rt of resourceTypes) {
|
||||
await api("POST", "resources/type/create", {
|
||||
name: rt.name,
|
||||
schema: rt.schema ?? {},
|
||||
description: rt.description ?? "",
|
||||
});
|
||||
}
|
||||
// The resource type search reads an index the server rebuilds every
|
||||
// RESOURCE_TYPE_EMBEDDINGS_CHECK_INTERVAL_SECS: a case must not start before it holds them.
|
||||
const last = resourceTypes[resourceTypes.length - 1]?.name;
|
||||
for (const deadline = Date.now() + RESOURCE_TYPE_INDEX_WAIT_MS; last; ) {
|
||||
const found: { name: string }[] = await api(
|
||||
"GET",
|
||||
`embeddings/query_resource_types?text=${encodeURIComponent(last)}&limit=10`,
|
||||
);
|
||||
if (found.some((rt) => rt.name === last)) break;
|
||||
if (Date.now() > deadline) {
|
||||
throw new Error(`the resource type search never found the seeded "${last}"`);
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 2_000));
|
||||
}
|
||||
for (const group of fixtures.groups ?? []) {
|
||||
await api("POST", "groups/create", { name: group.name, summary: group.summary });
|
||||
// A fixture names members who are not users of the instance; a membership row needs none.
|
||||
for (const member of group.members ?? []) {
|
||||
await psql(
|
||||
`INSERT INTO usr_to_group (workspace_id, usr, group_)
|
||||
VALUES (${literal(workspace)}, ${literal(member)}, ${literal(group.name)})`,
|
||||
"This fixture seeds group members",
|
||||
);
|
||||
}
|
||||
}
|
||||
for (const folder of fixtures.folders ?? []) {
|
||||
await api("POST", "folders/create", {
|
||||
name: folder.name,
|
||||
summary: folder.summary,
|
||||
owners: folder.owners ?? [],
|
||||
extra_perms: folder.extra_perms ?? {},
|
||||
});
|
||||
}
|
||||
for (const script of fixtures.scripts ?? []) {
|
||||
await api("POST", "scripts/create", {
|
||||
path: script.path,
|
||||
summary: script.summary,
|
||||
description: script.description ?? "",
|
||||
content: script.content,
|
||||
language: script.language,
|
||||
schema: script.schema ?? {},
|
||||
});
|
||||
}
|
||||
for (const flow of fixtures.flows ?? []) {
|
||||
await api("POST", "flows/create", {
|
||||
path: flow.path,
|
||||
summary: flow.summary,
|
||||
description: flow.description ?? "",
|
||||
value: flow.value,
|
||||
schema: flow.schema ?? {},
|
||||
});
|
||||
}
|
||||
for (const app of fixtures.apps ?? []) {
|
||||
await seedApp(api, app);
|
||||
}
|
||||
for (const variable of fixtures.variables ?? []) {
|
||||
await api("POST", "variables/create", {
|
||||
path: variable.path,
|
||||
value: variable.value,
|
||||
is_secret: variable.is_secret,
|
||||
description: variable.description ?? "",
|
||||
...(variable.labels ? { labels: variable.labels } : {}),
|
||||
});
|
||||
}
|
||||
for (const resource of fixtures.resources ?? []) {
|
||||
await api("POST", "resources/create", {
|
||||
path: resource.path,
|
||||
resource_type: resource.resource_type,
|
||||
value: resource.value ?? {},
|
||||
description: resource.description ?? "",
|
||||
});
|
||||
}
|
||||
await seedAiProviders(api, fixtures.aiProviders ?? []);
|
||||
for (const job of fixtures.jobs ?? []) {
|
||||
await seedJob(api, workspace, job);
|
||||
}
|
||||
for (const schedule of fixtures.schedules ?? []) {
|
||||
await api("POST", "schedules/create", {
|
||||
path: schedule.path,
|
||||
schedule: schedule.schedule,
|
||||
timezone: "UTC",
|
||||
script_path: schedule.script_path,
|
||||
is_flow: schedule.is_flow ?? false,
|
||||
args: {},
|
||||
enabled: schedule.enabled ?? true,
|
||||
summary: schedule.summary,
|
||||
});
|
||||
}
|
||||
await seedWorkers(fixtures.workers ?? []);
|
||||
const storage = !fixtures.objectStorage ? "none" : S3_ENDPOINT ? "runnable" : "unconfigured";
|
||||
if (storage === "unconfigured") {
|
||||
console.warn(
|
||||
`[ai_evals] ${workspace}: the fixture seeds objectStorage but WMILL_AI_EVAL_S3_ENDPOINT is not set; its pipeline will not run.`,
|
||||
);
|
||||
}
|
||||
if (storage === "runnable") {
|
||||
await seedObjectStorage(api, workspace, fixtures, scratchDbs);
|
||||
} else if (fixtures.ducklakes?.length) {
|
||||
await api("POST", "workspaces/edit_ducklake_config", {
|
||||
settings: {
|
||||
ducklakes: Object.fromEntries(
|
||||
fixtures.ducklakes.map((name) => [
|
||||
name,
|
||||
{
|
||||
catalog: { resource_type: "instance", resource_path: `${workspace}_${name}` },
|
||||
storage: { storage: null, path: name },
|
||||
},
|
||||
]),
|
||||
),
|
||||
},
|
||||
});
|
||||
}
|
||||
await seedDataMetrics(api, fixtures.dataMetrics ?? []);
|
||||
const datatables = fixtures.datatables ?? [];
|
||||
if (datatables.length > 1) {
|
||||
throw new Error("A global fixture seeds at most one datatable.");
|
||||
}
|
||||
if (datatables[0]) {
|
||||
scratchDbs.push(await seedDatatable(api, workspace, datatables[0]));
|
||||
}
|
||||
return storage;
|
||||
}
|
||||
|
||||
// Every attempt shares the bucket: seeded objects are the same for every attempt of a case, and
|
||||
// each DuckLake gets its own catalog database and data path, so attempts never see each
|
||||
// other's tables.
|
||||
async function seedObjectStorage(
|
||||
api: Api,
|
||||
workspace: string,
|
||||
fixtures: BenchmarkWorkspaceRunnables,
|
||||
scratchDbs: string[],
|
||||
): Promise<void> {
|
||||
await api("POST", "resources/create", {
|
||||
path: "u/admin/ai_evals_s3",
|
||||
resource_type: "s3",
|
||||
value: {
|
||||
bucket: process.env.WMILL_AI_EVAL_S3_BUCKET ?? "evals",
|
||||
region: process.env.WMILL_AI_EVAL_S3_REGION ?? "us-east-1",
|
||||
// The resource takes the host alone; `useSSL` carries the scheme.
|
||||
endPoint: S3_ENDPOINT!.replace(/^https?:\/\//, ""),
|
||||
useSSL: S3_ENDPOINT!.startsWith("https:"),
|
||||
accessKey: process.env.WMILL_AI_EVAL_S3_ACCESS_KEY ?? "minioadmin",
|
||||
secretKey: process.env.WMILL_AI_EVAL_S3_SECRET_KEY ?? "minioadmin",
|
||||
pathStyle: true,
|
||||
},
|
||||
});
|
||||
await api("POST", "workspaces/edit_large_file_storage_config", {
|
||||
large_file_storage: {
|
||||
type: "S3Storage",
|
||||
s3_resource_path: "$res:u/admin/ai_evals_s3",
|
||||
public_resource: false,
|
||||
advanced_permissions: null,
|
||||
secondary_storage: {},
|
||||
},
|
||||
});
|
||||
for (const file of fixtures.objectStorage?.files ?? []) {
|
||||
await api(
|
||||
"POST",
|
||||
`job_helpers/upload_s3_file?file_key=${encodeURIComponent(file.key)}`,
|
||||
new Blob([file.content], { type: "application/octet-stream" }),
|
||||
);
|
||||
}
|
||||
await configureLakes(api, workspace, fixtures.ducklakes ?? [], scratchDbs, "chat");
|
||||
}
|
||||
|
||||
/** Points each named DuckLake at a new, empty catalog database and data path. */
|
||||
async function configureLakes(
|
||||
api: Api,
|
||||
workspace: string,
|
||||
names: string[],
|
||||
scratchDbs: string[],
|
||||
generation: string,
|
||||
): Promise<void> {
|
||||
if (!names.length) return;
|
||||
await ensureRootPgResource(api);
|
||||
const ducklakes: Record<string, unknown> = {};
|
||||
for (const name of names) {
|
||||
// The workspace id ends with the attempt and a random suffix: keep that end.
|
||||
const database = `lake_${generation}_${name}_${workspace.replace(/-/g, "_").slice(-40)}`.slice(
|
||||
0,
|
||||
63,
|
||||
);
|
||||
await sql(api, ROOT_PG_RESOURCE, `CREATE DATABASE "${database}"`);
|
||||
scratchDbs.push(database);
|
||||
const path = `u/admin/ai_evals_lake_${name}_${generation}`;
|
||||
await api("POST", "resources/create", {
|
||||
path,
|
||||
resource_type: "postgresql",
|
||||
value: pgResource(database),
|
||||
});
|
||||
ducklakes[name] = {
|
||||
catalog: { resource_type: "postgresql", resource_path: path },
|
||||
storage: { storage: null, path: `ai_evals_lakes/${workspace}/${generation}/${name}` },
|
||||
};
|
||||
}
|
||||
await api("POST", "workspaces/edit_ducklake_config", { settings: { ducklakes } });
|
||||
}
|
||||
|
||||
function pgResource(dbname: string) {
|
||||
const root = new URL(DATATABLE_PG_URL);
|
||||
return {
|
||||
host: root.hostname,
|
||||
port: Number(root.port || 5432),
|
||||
user: decodeURIComponent(root.username),
|
||||
password: decodeURIComponent(root.password),
|
||||
dbname,
|
||||
sslmode: root.searchParams.get("sslmode") ?? "disable",
|
||||
};
|
||||
}
|
||||
|
||||
async function ensureRootPgResource(api: Api): Promise<void> {
|
||||
const exists = await api("GET", "resources/exists/u/admin/ai_evals_pg_root");
|
||||
if (exists === true) return;
|
||||
const root = new URL(DATATABLE_PG_URL);
|
||||
await api("POST", "resources/create", {
|
||||
path: "u/admin/ai_evals_pg_root",
|
||||
resource_type: "postgresql",
|
||||
value: pgResource(root.pathname.slice(1) || "postgres"),
|
||||
});
|
||||
}
|
||||
|
||||
async function seedApp(
|
||||
api: Api,
|
||||
app: NonNullable<BenchmarkWorkspaceRunnables["apps"]>[number],
|
||||
): Promise<void> {
|
||||
const policy = { execution_mode: "publisher", triggerables_v2: {} };
|
||||
if (app.rawApp === false) {
|
||||
await api("POST", "apps/create", {
|
||||
path: app.path,
|
||||
summary: app.summary,
|
||||
value: app.value,
|
||||
policy,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const form = new FormData();
|
||||
form.append(
|
||||
"app",
|
||||
JSON.stringify({
|
||||
path: app.path,
|
||||
summary: app.summary,
|
||||
value: { ...app.value, data: app.value.data ?? { tables: [] } },
|
||||
policy,
|
||||
}),
|
||||
);
|
||||
form.append("js", "");
|
||||
form.append("css", "");
|
||||
await api("POST", "apps/create_raw", form);
|
||||
}
|
||||
|
||||
async function seedAiProviders(
|
||||
api: Api,
|
||||
providers: NonNullable<BenchmarkWorkspaceRunnables["aiProviders"]>,
|
||||
): Promise<void> {
|
||||
if (!providers.length) return;
|
||||
const config: Record<string, unknown> = {};
|
||||
let defaultModel: { model: string; provider: string } | undefined;
|
||||
for (const provider of providers) {
|
||||
await api("POST", "resources/create", {
|
||||
path: provider.path,
|
||||
resource_type: provider.kind,
|
||||
value: {
|
||||
api_key: "ai-evals-placeholder",
|
||||
...(provider.base_url ? { base_url: provider.base_url } : {}),
|
||||
},
|
||||
});
|
||||
const models = provider.configuredModels ?? provider.models ?? [];
|
||||
config[provider.kind] = { resource_path: provider.path, models };
|
||||
if (provider.isDefault && models[0]) {
|
||||
defaultModel = { model: models[0], provider: provider.kind };
|
||||
}
|
||||
}
|
||||
await api("POST", "workspaces/edit_copilot_config", {
|
||||
providers: config,
|
||||
...(defaultModel ? { default_model: defaultModel } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
// A completed run with the fixture's id, path, args, logs and outcome. It is a preview job run
|
||||
// by the admin, so `createdBy` and a `script` job kind are not reproduced.
|
||||
async function seedJob(
|
||||
api: Api,
|
||||
workspace: string,
|
||||
job: NonNullable<BenchmarkWorkspaceRunnables["jobs"]>[number],
|
||||
): Promise<void> {
|
||||
const args = job.args ?? {};
|
||||
const id = job.id ?? randomUUID();
|
||||
const state = job.state ?? "completed";
|
||||
if (state === "suspended") {
|
||||
// A flow parked on an approval step: its first step suspends, as the fixture flow's does.
|
||||
await api("POST", `jobs/run/f/${job.scriptPath}?job_id=${id}`, args);
|
||||
await waitFor(`run ${id} to suspend`, async () => {
|
||||
const run = await api("GET", `jobs_u/get/${id}?no_logs=true`);
|
||||
return (run.flow_status?.modules ?? []).some(
|
||||
(module: { type?: string }) => module.type === "WaitingForEvents",
|
||||
);
|
||||
});
|
||||
} else if (state === "queued") {
|
||||
// Stays queued only on a tag no worker of the eval backend serves, as the fixture's does.
|
||||
await api("POST", `jobs/run/preview?job_id=${id}`, {
|
||||
content: "export async function main() {}",
|
||||
language: "bun",
|
||||
path: job.scriptPath,
|
||||
args,
|
||||
tag: job.tag,
|
||||
});
|
||||
} else if (state === "completed") {
|
||||
const content = [
|
||||
`export async function main(${Object.keys(args).join(", ")}) {`,
|
||||
` console.log(${JSON.stringify(job.logs ?? "")});`,
|
||||
job.success === false
|
||||
? ` throw new Error(${JSON.stringify(lastLine(job.logs) ?? "Job failed")});`
|
||||
: ` return ${JSON.stringify(job.result ?? null)};`,
|
||||
`}`,
|
||||
].join("\n");
|
||||
await api("POST", `jobs/run_wait_result/preview?job_id=${id}`, {
|
||||
content,
|
||||
language: "bun",
|
||||
path: job.scriptPath,
|
||||
args,
|
||||
}).catch((error) => {
|
||||
// A failing fixture run answers with its error, which is the point.
|
||||
if (job.success !== false) throw error;
|
||||
});
|
||||
} else {
|
||||
throw new Error(`A ${state} fixture run cannot be seeded on a real backend.`);
|
||||
}
|
||||
// Who ran it, when and where cannot be asked of the API: the run is rewritten to match.
|
||||
if (
|
||||
job.createdBy === undefined &&
|
||||
job.createdMinutesAgo === undefined &&
|
||||
job.durationMs === undefined &&
|
||||
job.tag === undefined &&
|
||||
job.schedulePath === undefined &&
|
||||
job.label === undefined
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const createdAt =
|
||||
job.createdMinutesAgo === undefined
|
||||
? "created_at"
|
||||
: `now() - interval '${Number(job.createdMinutesAgo)} minutes'`;
|
||||
await psql(
|
||||
`UPDATE v2_job SET created_at = ${createdAt},
|
||||
created_by = COALESCE(${literal(job.createdBy)}, created_by),
|
||||
tag = COALESCE(${literal(job.tag)}, tag),
|
||||
labels = COALESCE(${job.label === undefined ? "NULL" : `ARRAY[${literal(job.label)}]`}, labels)
|
||||
${job.schedulePath ? `, trigger = ${literal(job.schedulePath)}, trigger_kind = 'schedule'` : ""}
|
||||
WHERE id = ${literal(id)} AND workspace_id = ${literal(workspace)};
|
||||
UPDATE v2_job_queue q SET created_at = j.created_at, scheduled_for = j.created_at
|
||||
FROM v2_job j WHERE q.id = j.id AND q.id = ${literal(id)};
|
||||
UPDATE v2_job_completed c SET started_at = j.created_at,
|
||||
duration_ms = COALESCE(${literal(job.durationMs)}, c.duration_ms),
|
||||
completed_at = j.created_at + make_interval(secs => COALESCE(${literal(job.durationMs)}, c.duration_ms) / 1000.0)
|
||||
FROM v2_job j WHERE c.id = j.id AND c.id = ${literal(id)};`,
|
||||
"This fixture seeds who ran a run, when or where",
|
||||
);
|
||||
}
|
||||
|
||||
/** Fixture workers, listed beside the instance's own until the attempt ends. */
|
||||
async function seedWorkers(
|
||||
workers: NonNullable<BenchmarkWorkspaceRunnables["workers"]>,
|
||||
): Promise<void> {
|
||||
// ponytail: rows are instance-wide, so concurrent attempts of one case share them.
|
||||
for (const worker of workers) {
|
||||
await psql(
|
||||
`INSERT INTO worker_ping (worker, worker_instance, ping_at, started_at, ip, jobs_executed,
|
||||
custom_tags, worker_group)
|
||||
VALUES (${literal(worker.worker)}, ${literal(worker.worker)},
|
||||
now() - interval '${Number(worker.lastPingSecondsAgo ?? 0)} seconds', now(), 'ai-evals',
|
||||
${Number(worker.jobs_executed ?? 0)},
|
||||
ARRAY[${(worker.custom_tags ?? []).map(literal).join(", ")}]::varchar[],
|
||||
${literal(worker.worker_group)})
|
||||
ON CONFLICT (worker) DO UPDATE SET ping_at = EXCLUDED.ping_at`,
|
||||
"This fixture seeds workers",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function waitFor(what: string, done: () => Promise<boolean>): Promise<void> {
|
||||
for (const deadline = Date.now() + 60_000; !(await done()); ) {
|
||||
if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`);
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
}
|
||||
}
|
||||
|
||||
function lastLine(text: string | undefined): string | undefined {
|
||||
return text?.trim().split("\n").pop();
|
||||
}
|
||||
|
||||
// Metrics are catalogued from a DuckDB node's annotations when it is deployed.
|
||||
async function seedDataMetrics(
|
||||
api: Api,
|
||||
metrics: NonNullable<BenchmarkWorkspaceRunnables["dataMetrics"]>,
|
||||
): Promise<void> {
|
||||
const byScript = new Map<string, typeof metrics>();
|
||||
for (const metric of metrics) {
|
||||
const key = `${metric.script_path}\n${metric.table_path}`;
|
||||
byScript.set(key, [...(byScript.get(key) ?? []), metric]);
|
||||
}
|
||||
for (const [key, entries] of byScript) {
|
||||
const [scriptPath, tablePath] = key.split("\n");
|
||||
// `<lake>/<schema>.<table>`, as the catalog canonicalizes `ducklake://<lake>/<table>`.
|
||||
const [lake, qualified] = tablePath.split("/");
|
||||
const table = qualified.split(".").pop();
|
||||
const lines = [`-- materialize ducklake://${lake}/${table}`];
|
||||
for (const metric of entries) {
|
||||
lines.push(
|
||||
metric.kind === "measure"
|
||||
? `-- measure ${metric.name} = ${metric.expr}${metric.filter ? ` where ${metric.filter}` : ""}`
|
||||
: `-- dimension ${metric.name} = ${metric.expr}`,
|
||||
);
|
||||
}
|
||||
lines.push("SELECT 1");
|
||||
await api("POST", "scripts/create", {
|
||||
path: scriptPath,
|
||||
summary: "",
|
||||
description: "",
|
||||
content: lines.join("\n"),
|
||||
language: "duckdb",
|
||||
schema: {},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function seedDatatable(
|
||||
api: Api,
|
||||
workspace: string,
|
||||
seed: BenchmarkDatatableSeed,
|
||||
): Promise<string> {
|
||||
const database = `${workspace.replace(/-/g, "_")}_dt`.slice(0, 63);
|
||||
await ensureRootPgResource(api);
|
||||
await sql(api, ROOT_PG_RESOURCE, `CREATE DATABASE "${database}"`);
|
||||
await api("POST", "resources/create", {
|
||||
path: "u/admin/ai_evals_datatable",
|
||||
resource_type: "postgresql",
|
||||
value: pgResource(database),
|
||||
});
|
||||
await api("POST", "workspaces/edit_datatable_config", {
|
||||
settings: {
|
||||
datatables: {
|
||||
[seed.datatable_name]: {
|
||||
database: { resource_type: "postgresql", resource_path: "u/admin/ai_evals_datatable" },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
// A new datatable keeps its schema as migrations; a fixture says when this one does not.
|
||||
if (!seed.migrations_enabled) {
|
||||
await api("POST", `workspaces/disable_datatable_migrations/${seed.datatable_name}`);
|
||||
}
|
||||
const target = `datatable://${seed.datatable_name}`;
|
||||
for (const migration of seed.migrations ?? []) {
|
||||
await api("POST", `workspaces/upsert_datatable_migration/${seed.datatable_name}`, {
|
||||
timestamp: migration.timestamp,
|
||||
name: migration.name,
|
||||
code_up: migration.code_up,
|
||||
...(migration.code_down ? { code_down: migration.code_down } : {}),
|
||||
});
|
||||
if (migration.applied) {
|
||||
await api(
|
||||
"POST",
|
||||
`workspaces/run_datatable_migrations/${seed.datatable_name}?only=${migration.timestamp}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
const statements: string[] = [];
|
||||
for (const [schema, tables] of Object.entries(seed.schemas)) {
|
||||
statements.push(`CREATE SCHEMA IF NOT EXISTS "${schema}"`);
|
||||
for (const [table, { columns, rows }] of Object.entries(tables)) {
|
||||
const name = `"${schema}"."${table}"`;
|
||||
statements.push(
|
||||
`CREATE TABLE IF NOT EXISTS ${name} (${Object.entries(columns)
|
||||
.map(([column, type]) => `"${column}" ${type}`)
|
||||
.join(", ")})`,
|
||||
);
|
||||
for (const row of rows ?? []) {
|
||||
const keys = Object.keys(row);
|
||||
statements.push(
|
||||
`INSERT INTO ${name} (${keys.map((k) => `"${k}"`).join(", ")}) VALUES (${keys
|
||||
.map((k) => literal(row[k]))
|
||||
.join(", ")})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
await sql(api, target, statements.join(";\n"));
|
||||
return database;
|
||||
}
|
||||
|
||||
function literal(value: unknown): string {
|
||||
if (value === null || value === undefined) return "NULL";
|
||||
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
||||
const text = typeof value === "string" ? value : JSON.stringify(value);
|
||||
return `'${text.replace(/'/g, "''")}'`;
|
||||
}
|
||||
|
||||
async function sql(api: Api, database: string, content: string): Promise<void> {
|
||||
const result = await api("POST", "jobs/run_wait_result/preview", {
|
||||
content,
|
||||
language: "postgresql",
|
||||
args: { database },
|
||||
});
|
||||
if (result && typeof result === "object" && "error" in result) {
|
||||
throw new Error(`seeding SQL failed: ${JSON.stringify(result.error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Each attempt's user token carries its workspace, so the attempt revokes exactly its own. */
|
||||
function tokenLabel(workspace: string): string {
|
||||
return `ai-evals ${workspace}`;
|
||||
}
|
||||
|
||||
async function psql(
|
||||
sql: string,
|
||||
why = "This fixture's user is not the admin",
|
||||
): Promise<void> {
|
||||
if (!DATABASE_URL) {
|
||||
throw new Error(
|
||||
`${why}: set WMILL_AI_EVAL_DATABASE_URL to the eval backend's database URL so the harness can write it.`,
|
||||
);
|
||||
}
|
||||
await promisify(execFile)("psql", [DATABASE_URL, "-v", "ON_ERROR_STOP=1", "-qc", sql]);
|
||||
}
|
||||
@@ -138,7 +138,7 @@ export async function runEval<THelpers, TOutput>(
|
||||
// Accepts the run form exactly as the model prefilled it: there is nobody here to
|
||||
// edit the arguments, so a case can assert what the model proposed but never how
|
||||
// it reacts to the user changing something.
|
||||
requestRunArgs: async (_toolId, form) => form.args,
|
||||
requestRunArgs: async (_toolId, form) => ({ kind: "args", args: form.args }),
|
||||
...(pendingAnswers && {
|
||||
requestUserQuestion: async () => {
|
||||
const answer = pendingAnswers.shift();
|
||||
|
||||
@@ -1,262 +0,0 @@
|
||||
import { describe, expect, it } from 'bun:test'
|
||||
import { applyDatatableSql, type BenchmarkDatatableSeed } from './datatableSqlEngine'
|
||||
|
||||
function makeDatatable(): BenchmarkDatatableSeed {
|
||||
return {
|
||||
datatable_name: 'main',
|
||||
schemas: {
|
||||
public: {
|
||||
orders: {
|
||||
columns: { id: 'int4', customer_id: 'int4', total: 'numeric', status: 'text' },
|
||||
rows: [
|
||||
{ id: 1, customer_id: 1, total: 42.5, status: 'shipped' },
|
||||
{ id: 2, customer_id: 2, total: 19.99, status: 'pending' },
|
||||
{ id: 3, customer_id: 1, total: 88, status: 'shipped' }
|
||||
]
|
||||
},
|
||||
customers: {
|
||||
columns: { id: 'int4', name: 'text' },
|
||||
rows: [{ id: 1, name: 'Alice' }]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('SELECT', () => {
|
||||
it('returns the referenced table rows', () => {
|
||||
const dt = makeDatatable()
|
||||
expect(applyDatatableSql(dt, 'SELECT id, name FROM customers').rows).toEqual([
|
||||
{ id: 1, name: 'Alice' }
|
||||
])
|
||||
})
|
||||
|
||||
it('falls back to the first table when no known table is referenced', () => {
|
||||
const dt = makeDatatable()
|
||||
expect(applyDatatableSql(dt, 'select 1').rows).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('resolves a schema-qualified table', () => {
|
||||
const dt = makeDatatable()
|
||||
expect(applyDatatableSql(dt, 'SELECT * FROM public.customers').rows).toEqual([
|
||||
{ id: 1, name: 'Alice' }
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('CREATE TABLE', () => {
|
||||
it('adds a table with parsed columns, skipping table constraints and FK clauses', () => {
|
||||
const dt = makeDatatable()
|
||||
const result = applyDatatableSql(
|
||||
dt,
|
||||
'CREATE TABLE public.refunds (\n order_id int4 NOT NULL REFERENCES public.orders(id),\n amount numeric(10,2),\n PRIMARY KEY (order_id)\n)'
|
||||
)
|
||||
expect(result.rows).toEqual([])
|
||||
expect(dt.schemas.public.refunds).toEqual({
|
||||
columns: { order_id: 'int4', amount: 'numeric(10,2)' },
|
||||
rows: []
|
||||
})
|
||||
})
|
||||
|
||||
it('defaults an unqualified table to the public schema', () => {
|
||||
const dt = makeDatatable()
|
||||
applyDatatableSql(dt, 'CREATE TABLE notes (id int4, body text)')
|
||||
expect(dt.schemas.public.notes.columns).toEqual({ id: 'int4', body: 'text' })
|
||||
})
|
||||
|
||||
it('is a no-op for an existing table with IF NOT EXISTS', () => {
|
||||
const dt = makeDatatable()
|
||||
applyDatatableSql(dt, 'CREATE TABLE IF NOT EXISTS public.orders (x int4)')
|
||||
expect(Object.keys(dt.schemas.public.orders.columns)).toContain('status')
|
||||
})
|
||||
})
|
||||
|
||||
describe('DROP TABLE', () => {
|
||||
it('removes the table', () => {
|
||||
const dt = makeDatatable()
|
||||
applyDatatableSql(dt, 'DROP TABLE IF EXISTS public.customers')
|
||||
expect(dt.schemas.public.customers).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('INSERT', () => {
|
||||
it('appends a row using an explicit column list', () => {
|
||||
const dt = makeDatatable()
|
||||
applyDatatableSql(dt, "INSERT INTO customers (id, name) VALUES (2, 'Bob')")
|
||||
expect(dt.schemas.public.customers.rows).toContainEqual({ id: 2, name: 'Bob' })
|
||||
})
|
||||
|
||||
it('infers columns from the table when none are given, and appends multiple tuples', () => {
|
||||
const dt = makeDatatable()
|
||||
applyDatatableSql(dt, "INSERT INTO customers VALUES (2, 'Bob'), (3, 'Carol')")
|
||||
expect(dt.schemas.public.customers.rows).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('returns the inserted rows when RETURNING is present', () => {
|
||||
const dt = makeDatatable()
|
||||
const result = applyDatatableSql(
|
||||
dt,
|
||||
"INSERT INTO customers (id, name) VALUES (2, 'Bob') RETURNING *"
|
||||
)
|
||||
expect(result.rows).toEqual([{ id: 2, name: 'Bob' }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('UPDATE', () => {
|
||||
it('updates only the rows matching an equality WHERE', () => {
|
||||
const dt = makeDatatable()
|
||||
const result = applyDatatableSql(
|
||||
dt,
|
||||
"UPDATE public.orders SET status = 'shipped' WHERE id = 2"
|
||||
)
|
||||
expect(result.rows).toEqual([])
|
||||
expect(dt.schemas.public.orders.rows?.find((r) => r.id === 2)?.status).toBe('shipped')
|
||||
expect(dt.schemas.public.orders.rows?.find((r) => r.id === 1)?.status).toBe('shipped')
|
||||
})
|
||||
|
||||
it('strips a Postgres cast in the WHERE value', () => {
|
||||
const dt = makeDatatable()
|
||||
applyDatatableSql(dt, "UPDATE orders SET status = 'done' WHERE id = 2::int4")
|
||||
expect(dt.schemas.public.orders.rows?.find((r) => r.id === 2)?.status).toBe('done')
|
||||
})
|
||||
|
||||
it('matches multiple AND predicates including a numeric literal', () => {
|
||||
const dt = makeDatatable()
|
||||
applyDatatableSql(
|
||||
dt,
|
||||
"UPDATE orders SET status = 'done' WHERE customer_id = 2 AND total = 19.99"
|
||||
)
|
||||
expect(dt.schemas.public.orders.rows?.find((r) => r.id === 2)?.status).toBe('done')
|
||||
expect(dt.schemas.public.orders.rows?.find((r) => r.id === 1)?.status).toBe('shipped')
|
||||
})
|
||||
|
||||
it('updates every row when there is no WHERE', () => {
|
||||
const dt = makeDatatable()
|
||||
applyDatatableSql(dt, "UPDATE orders SET status = 'archived'")
|
||||
expect(dt.schemas.public.orders.rows?.every((r) => r.status === 'archived')).toBe(true)
|
||||
})
|
||||
|
||||
it('returns the affected rows when RETURNING is present', () => {
|
||||
const dt = makeDatatable()
|
||||
const result = applyDatatableSql(
|
||||
dt,
|
||||
"UPDATE orders SET status = 'shipped' WHERE id = 2 RETURNING *"
|
||||
)
|
||||
expect(result.rows).toHaveLength(1)
|
||||
expect(result.rows[0]).toMatchObject({ id: 2, status: 'shipped' })
|
||||
})
|
||||
|
||||
it('affects no rows when the WHERE clause cannot be parsed', () => {
|
||||
const dt = makeDatatable()
|
||||
applyDatatableSql(dt, "UPDATE orders SET status = 'x' WHERE total > 20")
|
||||
expect(dt.schemas.public.orders.rows?.some((r) => r.status === 'x')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE', () => {
|
||||
it('removes only the matching rows', () => {
|
||||
const dt = makeDatatable()
|
||||
applyDatatableSql(dt, 'DELETE FROM orders WHERE id = 2')
|
||||
expect(dt.schemas.public.orders.rows?.map((r) => r.id)).toEqual([1, 3])
|
||||
})
|
||||
|
||||
it('returns the removed rows when RETURNING is present', () => {
|
||||
const dt = makeDatatable()
|
||||
const result = applyDatatableSql(dt, 'DELETE FROM orders WHERE id = 2 RETURNING *')
|
||||
expect(result.rows).toEqual([{ id: 2, customer_id: 2, total: 19.99, status: 'pending' }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('writes are reflected by later reads', () => {
|
||||
it('UPDATE then SELECT sees the new value (the verify-loop fix)', () => {
|
||||
const dt = makeDatatable()
|
||||
applyDatatableSql(dt, "UPDATE orders SET status = 'shipped' WHERE id = 2")
|
||||
const seen = applyDatatableSql(dt, 'SELECT * FROM orders').rows
|
||||
expect(seen.find((r) => r.id === 2)?.status).toBe('shipped')
|
||||
})
|
||||
|
||||
it('INSERT then SELECT sees the new row', () => {
|
||||
const dt = makeDatatable()
|
||||
applyDatatableSql(dt, "INSERT INTO customers (id, name) VALUES (9, 'Zed')")
|
||||
const seen = applyDatatableSql(dt, 'SELECT * FROM customers').rows
|
||||
expect(seen).toContainEqual({ id: 9, name: 'Zed' })
|
||||
})
|
||||
|
||||
it('CREATE then SELECT on the new table returns its (empty) rows', () => {
|
||||
const dt = makeDatatable()
|
||||
applyDatatableSql(dt, 'CREATE TABLE public.refunds (order_id int4, amount numeric)')
|
||||
expect(applyDatatableSql(dt, 'SELECT * FROM refunds').rows).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('system-catalog queries reflect the current tables/columns', () => {
|
||||
it('lists current tables (including a freshly created one) via information_schema.tables', () => {
|
||||
const dt = makeDatatable()
|
||||
applyDatatableSql(dt, 'CREATE TABLE public.refunds (order_id int4)')
|
||||
const rows = applyDatatableSql(
|
||||
dt,
|
||||
"SELECT table_name FROM information_schema.tables WHERE table_name = 'refunds'"
|
||||
).rows
|
||||
expect(rows.map((r) => r.table_name)).toContain('refunds')
|
||||
})
|
||||
|
||||
it('does not list a dropped table', () => {
|
||||
const dt = makeDatatable()
|
||||
applyDatatableSql(dt, 'DROP TABLE public.customers')
|
||||
const rows = applyDatatableSql(dt, 'SELECT table_name FROM information_schema.tables').rows
|
||||
expect(rows.map((r) => r.table_name)).not.toContain('customers')
|
||||
})
|
||||
|
||||
it('reports columns via information_schema.columns', () => {
|
||||
const dt = makeDatatable()
|
||||
const rows = applyDatatableSql(
|
||||
dt,
|
||||
"SELECT column_name FROM information_schema.columns WHERE table_name = 'orders'"
|
||||
).rows
|
||||
expect(rows.map((r) => r.column_name)).toContain('status')
|
||||
})
|
||||
})
|
||||
|
||||
describe('parser robustness (string/paren-aware splitting)', () => {
|
||||
it('does not treat the word "returning" inside a string value as a RETURNING clause', () => {
|
||||
const dt = makeDatatable()
|
||||
const result = applyDatatableSql(
|
||||
dt,
|
||||
"INSERT INTO customers (id, name) VALUES (5, 'is returning soon')"
|
||||
)
|
||||
expect(result.rows).toEqual([])
|
||||
expect(dt.schemas.public.customers.rows).toContainEqual({ id: 5, name: 'is returning soon' })
|
||||
})
|
||||
|
||||
it('does not split on the word "where" inside a SET string value', () => {
|
||||
const dt = makeDatatable()
|
||||
applyDatatableSql(dt, "UPDATE orders SET status = 'ship where ordered' WHERE id = 2")
|
||||
expect(dt.schemas.public.orders.rows?.find((r) => r.id === 2)?.status).toBe('ship where ordered')
|
||||
expect(dt.schemas.public.orders.rows?.find((r) => r.id === 1)?.status).toBe('shipped')
|
||||
})
|
||||
|
||||
it('keeps INSERT tuples intact when a value contains a function call', () => {
|
||||
const dt = makeDatatable()
|
||||
applyDatatableSql(dt, "INSERT INTO customers (id, name) VALUES (6, coalesce(NULL, 'x'))")
|
||||
expect(dt.schemas.public.customers.rows).toHaveLength(2)
|
||||
expect(dt.schemas.public.customers.rows?.[1]).toMatchObject({ id: 6 })
|
||||
})
|
||||
|
||||
it('CREATE TABLE ignores a trailing semicolon-separated statement', () => {
|
||||
const dt = makeDatatable()
|
||||
applyDatatableSql(
|
||||
dt,
|
||||
'CREATE TABLE public.refunds (id int4, amount numeric); INSERT INTO refunds VALUES (1, 5)'
|
||||
)
|
||||
expect(dt.schemas.public.refunds.columns).toEqual({ id: 'int4', amount: 'numeric' })
|
||||
expect(dt.schemas.public.refunds.rows).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('unparseable statements are a safe no-op', () => {
|
||||
it('returns [] and does not throw', () => {
|
||||
const dt = makeDatatable()
|
||||
expect(applyDatatableSql(dt, 'VACUUM ANALYZE').rows).toEqual([])
|
||||
expect(applyDatatableSql(dt, 'GRANT SELECT ON orders TO someone').rows).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -1,552 +0,0 @@
|
||||
/**
|
||||
* A deliberately small, best-effort SQL engine for the benchmark datatable mock.
|
||||
*
|
||||
* This is NOT a real SQL implementation — it exists only so that writes a model
|
||||
* issues during an eval (`CREATE TABLE`, `INSERT`, `UPDATE`, `DELETE`, `DROP`)
|
||||
* become visible to its later reads (`list_datatables`, `get_datatable_table_schema`,
|
||||
* `SELECT`). Without that, a model that re-queries to verify a write sees stale
|
||||
* seed data, concludes the write failed, and loops until it exhausts its turns.
|
||||
*
|
||||
* It parses only the common statement shapes models produce. Anything it cannot
|
||||
* parse is a no-op success (it never throws) — behavioral evals assert that the
|
||||
* right statement was issued, not its exact data effects. Notable limits:
|
||||
* - `SELECT` returns all rows of the referenced (or first) table — no WHERE
|
||||
* filtering, projection, joins, or aggregation.
|
||||
* - `WHERE` supports `col = value` predicates joined by `AND` only; an
|
||||
* unparseable WHERE on UPDATE/DELETE affects zero rows (never the whole table).
|
||||
*/
|
||||
|
||||
/** One seeded datatable table: its columns (col -> compact_type) and optional rows. */
|
||||
export interface BenchmarkDatatableTableSeed {
|
||||
columns: Record<string, string>
|
||||
rows?: Record<string, unknown>[]
|
||||
}
|
||||
|
||||
/** A seeded datatable: `datatable_name` plus a `schema -> table -> seed` map. */
|
||||
export interface BenchmarkDatatableSeed {
|
||||
datatable_name: string
|
||||
schemas: {
|
||||
[schema: string]: {
|
||||
[table: string]: BenchmarkDatatableTableSeed
|
||||
}
|
||||
}
|
||||
/** Whether the datatable keeps its schema as migrations. */
|
||||
migrations_enabled?: boolean
|
||||
migrations?: BenchmarkDatatableMigrationSeed[]
|
||||
}
|
||||
|
||||
export interface BenchmarkDatatableMigrationSeed {
|
||||
timestamp: number
|
||||
name: string
|
||||
code_up: string
|
||||
code_down?: string
|
||||
applied?: boolean
|
||||
}
|
||||
|
||||
export interface DatatableSqlResult {
|
||||
rows: Record<string, unknown>[]
|
||||
}
|
||||
|
||||
const DEFAULT_SCHEMA = 'public'
|
||||
|
||||
type ParsedRef = { schema: string; table: string }
|
||||
type Predicate = { column: string; value: unknown }
|
||||
|
||||
/**
|
||||
* Apply one SQL statement to `datatable` IN PLACE and return the result rows.
|
||||
* SELECT returns the referenced/first table's rows; a mutation returns its
|
||||
* affected rows when it has a RETURNING clause, otherwise `[]`.
|
||||
*/
|
||||
export function applyDatatableSql(
|
||||
datatable: BenchmarkDatatableSeed,
|
||||
sql: string
|
||||
): DatatableSqlResult {
|
||||
const statement = stripTrailingSemicolon(sql.trim())
|
||||
if (/^\s*(with|select)\b/i.test(statement)) {
|
||||
return { rows: selectRows(datatable, statement) }
|
||||
}
|
||||
if (/^\s*create\s+table\b/i.test(statement)) {
|
||||
return { rows: applyCreateTable(datatable, statement) }
|
||||
}
|
||||
if (/^\s*drop\s+table\b/i.test(statement)) {
|
||||
return { rows: applyDropTable(datatable, statement) }
|
||||
}
|
||||
if (/^\s*insert\s+into\b/i.test(statement)) {
|
||||
return { rows: applyInsert(datatable, statement) }
|
||||
}
|
||||
if (/^\s*update\b/i.test(statement)) {
|
||||
return { rows: applyUpdate(datatable, statement) }
|
||||
}
|
||||
if (/^\s*delete\s+from\b/i.test(statement)) {
|
||||
return { rows: applyDelete(datatable, statement) }
|
||||
}
|
||||
return { rows: [] }
|
||||
}
|
||||
|
||||
// ============= Reads =============
|
||||
|
||||
function selectRows(
|
||||
datatable: BenchmarkDatatableSeed,
|
||||
sql: string
|
||||
): Record<string, unknown>[] {
|
||||
const fromRef = sql.match(/\bfrom\s+([a-zA-Z_"][\w."]*)/i)?.[1]
|
||||
if (fromRef) {
|
||||
const catalog = catalogRows(datatable, fromRef)
|
||||
if (catalog) {
|
||||
return catalog
|
||||
}
|
||||
}
|
||||
const table = fromRef ? resolveTable(datatable, fromRef) : undefined
|
||||
const seed = table ?? firstTable(datatable)
|
||||
return seed?.rows ?? []
|
||||
}
|
||||
|
||||
/**
|
||||
* Synthesize rows for a system-catalog query so a model verifying a `CREATE`/`DROP`
|
||||
* via `information_schema.tables` / `.columns` (or `pg_tables`) sees the current
|
||||
* tables/columns instead of fallback data. WHERE is not applied, so the model gets
|
||||
* the full set and finds (or no longer finds) the table it just changed.
|
||||
* Returns `undefined` for non-catalog refs so normal table resolution proceeds.
|
||||
*/
|
||||
function catalogRows(
|
||||
datatable: BenchmarkDatatableSeed,
|
||||
ref: string
|
||||
): Record<string, unknown>[] | undefined {
|
||||
const normalized = ref.toLowerCase().replace(/"/g, '')
|
||||
const name = normalized.split('.').pop()
|
||||
const isCatalog = normalized.includes('information_schema.') || normalized.startsWith('pg_')
|
||||
if (!isCatalog) {
|
||||
return undefined
|
||||
}
|
||||
const tables = allTables(datatable)
|
||||
if (name === 'tables' || name === 'pg_tables') {
|
||||
return tables.map(({ schema, table }) => ({
|
||||
table_schema: schema,
|
||||
table_name: table,
|
||||
schemaname: schema,
|
||||
tablename: table
|
||||
}))
|
||||
}
|
||||
if (name === 'columns') {
|
||||
return tables.flatMap(({ schema, table, seed }) =>
|
||||
Object.entries(seed.columns).map(([column, type]) => ({
|
||||
table_schema: schema,
|
||||
table_name: table,
|
||||
column_name: column,
|
||||
data_type: type
|
||||
}))
|
||||
)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
function allTables(
|
||||
datatable: BenchmarkDatatableSeed
|
||||
): { schema: string; table: string; seed: BenchmarkDatatableTableSeed }[] {
|
||||
return Object.entries(datatable.schemas).flatMap(([schema, tables]) =>
|
||||
Object.entries(tables).map(([table, seed]) => ({ schema, table, seed }))
|
||||
)
|
||||
}
|
||||
|
||||
// ============= DDL =============
|
||||
|
||||
function applyCreateTable(
|
||||
datatable: BenchmarkDatatableSeed,
|
||||
sql: string
|
||||
): Record<string, unknown>[] {
|
||||
const head = sql.match(
|
||||
/^\s*create\s+table\s+(?:if\s+not\s+exists\s+)?([a-zA-Z_"][\w."]*)/i
|
||||
)
|
||||
// The first top-level paren group is the column-definition list; using it (rather
|
||||
// than a greedy `(...)` capture) ignores any trailing `;`-separated statement.
|
||||
const columnText = extractParenGroups(sql)[0]
|
||||
if (!head || columnText === undefined) {
|
||||
return []
|
||||
}
|
||||
const { schema, table } = parseRef(head[1])
|
||||
const existing = datatable.schemas[schema]?.[table]
|
||||
if (existing) {
|
||||
return []
|
||||
}
|
||||
const columns: Record<string, string> = {}
|
||||
for (const rawDef of splitTopLevel(columnText)) {
|
||||
const def = rawDef.trim()
|
||||
if (!def || isTableConstraint(def)) {
|
||||
continue
|
||||
}
|
||||
const tokens = def.split(/\s+/)
|
||||
const column = unquoteIdentifier(tokens[0])
|
||||
if (!column) {
|
||||
continue
|
||||
}
|
||||
columns[column] = tokens[1] ?? 'text'
|
||||
}
|
||||
if (!datatable.schemas[schema]) {
|
||||
datatable.schemas[schema] = {}
|
||||
}
|
||||
datatable.schemas[schema][table] = { columns, rows: [] }
|
||||
return []
|
||||
}
|
||||
|
||||
function applyDropTable(
|
||||
datatable: BenchmarkDatatableSeed,
|
||||
sql: string
|
||||
): Record<string, unknown>[] {
|
||||
const match = sql.match(
|
||||
/^\s*drop\s+table\s+(?:if\s+exists\s+)?([a-zA-Z_"][\w."]*)/i
|
||||
)
|
||||
if (!match) {
|
||||
return []
|
||||
}
|
||||
const { schema, table } = parseRef(match[1])
|
||||
if (datatable.schemas[schema]?.[table]) {
|
||||
delete datatable.schemas[schema][table]
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
// ============= DML =============
|
||||
|
||||
function applyInsert(
|
||||
datatable: BenchmarkDatatableSeed,
|
||||
sql: string
|
||||
): Record<string, unknown>[] {
|
||||
const { body, returning } = splitOffReturning(sql)
|
||||
const match = body.match(
|
||||
/^\s*insert\s+into\s+([a-zA-Z_"][\w."]*)\s*(?:\(([^)]*)\))?\s*values\s*([\s\S]+)$/i
|
||||
)
|
||||
if (!match) {
|
||||
return []
|
||||
}
|
||||
const table = resolveTable(datatable, match[1])
|
||||
if (!table) {
|
||||
return []
|
||||
}
|
||||
const columns = match[2]
|
||||
? splitTopLevel(match[2]).map((entry) => unquoteIdentifier(entry.trim()))
|
||||
: Object.keys(table.columns)
|
||||
const inserted: Record<string, unknown>[] = []
|
||||
for (const tuple of extractParenGroups(match[3])) {
|
||||
const values = splitTopLevel(tuple).map((entry) => parseValue(entry))
|
||||
const row: Record<string, unknown> = {}
|
||||
columns.forEach((column, index) => {
|
||||
row[column] = values[index]
|
||||
})
|
||||
inserted.push(row)
|
||||
}
|
||||
table.rows ??= []
|
||||
table.rows.push(...inserted)
|
||||
return returning ? inserted : []
|
||||
}
|
||||
|
||||
function applyUpdate(
|
||||
datatable: BenchmarkDatatableSeed,
|
||||
sql: string
|
||||
): Record<string, unknown>[] {
|
||||
const { body, returning } = splitOffReturning(sql)
|
||||
const match = body.match(/^\s*update\s+([a-zA-Z_"][\w."]*)\s+set\s+([\s\S]+)$/i)
|
||||
if (!match) {
|
||||
return []
|
||||
}
|
||||
const table = resolveTable(datatable, match[1])
|
||||
if (!table) {
|
||||
return []
|
||||
}
|
||||
let assignmentText = match[2]
|
||||
let whereText: string | undefined
|
||||
const whereMatch = maskForClauseScan(assignmentText).match(/\swhere\s/i)
|
||||
if (whereMatch && whereMatch.index !== undefined) {
|
||||
whereText = assignmentText.slice(whereMatch.index + whereMatch[0].length)
|
||||
assignmentText = assignmentText.slice(0, whereMatch.index)
|
||||
}
|
||||
const predicates = parsePredicates(whereText)
|
||||
if (predicates === null) {
|
||||
return []
|
||||
}
|
||||
const assignments: Record<string, unknown> = {}
|
||||
for (const entry of splitTopLevel(assignmentText)) {
|
||||
const pair = entry.match(/^\s*([a-zA-Z_"][\w."]*)\s*=\s*([\s\S]+?)\s*$/)
|
||||
if (pair) {
|
||||
assignments[lastIdentifier(pair[1])] = parseValue(pair[2])
|
||||
}
|
||||
}
|
||||
const affected = (table.rows ?? []).filter((row) => rowMatches(row, predicates))
|
||||
for (const row of affected) {
|
||||
Object.assign(row, assignments)
|
||||
}
|
||||
return returning ? affected : []
|
||||
}
|
||||
|
||||
function applyDelete(
|
||||
datatable: BenchmarkDatatableSeed,
|
||||
sql: string
|
||||
): Record<string, unknown>[] {
|
||||
const { body, returning } = splitOffReturning(sql)
|
||||
const match = body.match(/^\s*delete\s+from\s+([a-zA-Z_"][\w."]*)\s*([\s\S]*)$/i)
|
||||
if (!match) {
|
||||
return []
|
||||
}
|
||||
const table = resolveTable(datatable, match[1])
|
||||
if (!table) {
|
||||
return []
|
||||
}
|
||||
const whereText = match[2].replace(/^\s*where\s+/i, '').trim() || undefined
|
||||
const predicates = parsePredicates(whereText)
|
||||
if (predicates === null) {
|
||||
return []
|
||||
}
|
||||
const rows = table.rows ?? []
|
||||
const removed = rows.filter((row) => rowMatches(row, predicates))
|
||||
table.rows = rows.filter((row) => !rowMatches(row, predicates))
|
||||
return returning ? removed : []
|
||||
}
|
||||
|
||||
// ============= Parsing helpers =============
|
||||
|
||||
function resolveTable(
|
||||
datatable: BenchmarkDatatableSeed,
|
||||
ref: string
|
||||
): BenchmarkDatatableTableSeed | undefined {
|
||||
const { schema, table } = parseRef(ref)
|
||||
const direct = datatable.schemas[schema]?.[table]
|
||||
if (direct) {
|
||||
return direct
|
||||
}
|
||||
// Bare table name: fall back to searching every schema for a matching table.
|
||||
if (!ref.includes('.')) {
|
||||
for (const tables of Object.values(datatable.schemas)) {
|
||||
if (tables[table]) {
|
||||
return tables[table]
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
function firstTable(
|
||||
datatable: BenchmarkDatatableSeed
|
||||
): BenchmarkDatatableTableSeed | undefined {
|
||||
for (const tables of Object.values(datatable.schemas)) {
|
||||
for (const seed of Object.values(tables)) {
|
||||
return seed
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
function parseRef(ref: string): ParsedRef {
|
||||
const parts = ref.split('.').map(unquoteIdentifier)
|
||||
if (parts.length >= 2) {
|
||||
return { schema: parts[parts.length - 2], table: parts[parts.length - 1] }
|
||||
}
|
||||
return { schema: DEFAULT_SCHEMA, table: parts[0] }
|
||||
}
|
||||
|
||||
/** A WHERE clause with no parseable form returns `null`; absent WHERE returns `[]` (match all). */
|
||||
function parsePredicates(whereText: string | undefined): Predicate[] | null {
|
||||
if (whereText === undefined || whereText.trim() === '') {
|
||||
return []
|
||||
}
|
||||
const predicates: Predicate[] = []
|
||||
for (const part of whereText.split(/\s+and\s+/i)) {
|
||||
const match = part.match(/^\s*([a-zA-Z_"][\w."]*)\s*=\s*([\s\S]+?)\s*$/)
|
||||
if (!match) {
|
||||
return null
|
||||
}
|
||||
predicates.push({ column: lastIdentifier(match[1]), value: parseValue(match[2]) })
|
||||
}
|
||||
return predicates
|
||||
}
|
||||
|
||||
function rowMatches(row: Record<string, unknown>, predicates: Predicate[]): boolean {
|
||||
return predicates.every((predicate) => looseEquals(row[predicate.column], predicate.value))
|
||||
}
|
||||
|
||||
function looseEquals(left: unknown, right: unknown): boolean {
|
||||
if (left === null || left === undefined) {
|
||||
return right === null || right === undefined
|
||||
}
|
||||
if (typeof left === 'number' && typeof right === 'number') {
|
||||
return left === right
|
||||
}
|
||||
return String(left) === String(right)
|
||||
}
|
||||
|
||||
function parseValue(raw: string): unknown {
|
||||
// Drop a trailing Postgres cast (e.g. `2::int4`) before interpreting the literal.
|
||||
const token = raw.trim().replace(/::\s*[a-zA-Z_][\w]*(\([^)]*\))?\s*$/, '').trim()
|
||||
const stringMatch = token.match(/^'([\s\S]*)'$/)
|
||||
if (stringMatch) {
|
||||
return stringMatch[1].replace(/''/g, "'")
|
||||
}
|
||||
if (/^-?\d+(\.\d+)?$/.test(token)) {
|
||||
return Number(token)
|
||||
}
|
||||
if (/^true$/i.test(token)) {
|
||||
return true
|
||||
}
|
||||
if (/^false$/i.test(token)) {
|
||||
return false
|
||||
}
|
||||
if (/^null$/i.test(token)) {
|
||||
return null
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
function splitOffReturning(sql: string): { body: string; returning: boolean } {
|
||||
const match = maskForClauseScan(sql).match(/\sreturning\s/i)
|
||||
if (!match || match.index === undefined) {
|
||||
return { body: sql, returning: false }
|
||||
}
|
||||
return { body: sql.slice(0, match.index), returning: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* A same-length copy of `sql` with the contents of single-quoted strings and
|
||||
* parenthesized groups blanked to spaces, so a top-level keyword scan
|
||||
* (WHERE / RETURNING) cannot match inside a string literal or a subquery. Index
|
||||
* positions in the result map 1:1 back onto the original.
|
||||
*/
|
||||
function maskForClauseScan(sql: string): string {
|
||||
let masked = ''
|
||||
let depth = 0
|
||||
let inString = false
|
||||
for (let i = 0; i < sql.length; i++) {
|
||||
const char = sql[i]
|
||||
if (inString) {
|
||||
if (char === "'") {
|
||||
if (sql[i + 1] === "'") {
|
||||
masked += ' '
|
||||
i++
|
||||
continue
|
||||
}
|
||||
inString = false
|
||||
}
|
||||
masked += ' '
|
||||
continue
|
||||
}
|
||||
if (char === "'") {
|
||||
inString = true
|
||||
masked += ' '
|
||||
} else if (char === '(') {
|
||||
depth++
|
||||
masked += ' '
|
||||
} else if (char === ')') {
|
||||
depth = Math.max(0, depth - 1)
|
||||
masked += ' '
|
||||
} else {
|
||||
masked += depth > 0 ? ' ' : char
|
||||
}
|
||||
}
|
||||
return masked
|
||||
}
|
||||
|
||||
/**
|
||||
* Inner text of each top-level `( ... )` group in `input`, honoring nested parens
|
||||
* (e.g. `now()`, `numeric(10,2)`) and single-quoted strings. Used for the CREATE
|
||||
* column-definition group and INSERT value tuples.
|
||||
*/
|
||||
function extractParenGroups(input: string): string[] {
|
||||
const groups: string[] = []
|
||||
let depth = 0
|
||||
let inString = false
|
||||
let current = ''
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
const char = input[i]
|
||||
if (inString) {
|
||||
current += char
|
||||
if (char === "'") {
|
||||
if (input[i + 1] === "'") {
|
||||
current += input[++i]
|
||||
} else {
|
||||
inString = false
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (char === "'") {
|
||||
inString = true
|
||||
current += char
|
||||
} else if (char === '(') {
|
||||
depth++
|
||||
if (depth === 1) {
|
||||
current = ''
|
||||
} else {
|
||||
current += char
|
||||
}
|
||||
} else if (char === ')') {
|
||||
depth = Math.max(0, depth - 1)
|
||||
if (depth === 0) {
|
||||
groups.push(current)
|
||||
current = ''
|
||||
} else {
|
||||
current += char
|
||||
}
|
||||
} else if (depth > 0) {
|
||||
current += char
|
||||
}
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
/** Split on commas that are not inside parentheses or single-quoted strings. */
|
||||
function splitTopLevel(input: string): string[] {
|
||||
const parts: string[] = []
|
||||
let depth = 0
|
||||
let inString = false
|
||||
let current = ''
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
const char = input[i]
|
||||
if (inString) {
|
||||
current += char
|
||||
if (char === "'") {
|
||||
if (input[i + 1] === "'") {
|
||||
current += input[++i]
|
||||
} else {
|
||||
inString = false
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (char === "'") {
|
||||
inString = true
|
||||
current += char
|
||||
} else if (char === '(') {
|
||||
depth++
|
||||
current += char
|
||||
} else if (char === ')') {
|
||||
depth = Math.max(0, depth - 1)
|
||||
current += char
|
||||
} else if (char === ',' && depth === 0) {
|
||||
parts.push(current)
|
||||
current = ''
|
||||
} else {
|
||||
current += char
|
||||
}
|
||||
}
|
||||
if (current.trim() !== '') {
|
||||
parts.push(current)
|
||||
}
|
||||
return parts
|
||||
}
|
||||
|
||||
function isTableConstraint(def: string): boolean {
|
||||
return /^(primary\s+key|foreign\s+key|constraint|unique|check|exclude|like)\b/i.test(def)
|
||||
}
|
||||
|
||||
function unquoteIdentifier(identifier: string): string {
|
||||
const trimmed = identifier.trim()
|
||||
const quoted = trimmed.match(/^"([\s\S]*)"$/)
|
||||
return quoted ? quoted[1] : trimmed
|
||||
}
|
||||
|
||||
/** For a qualified reference like `orders.id`, keep only the final identifier. */
|
||||
function lastIdentifier(reference: string): string {
|
||||
const parts = reference.split('.')
|
||||
return unquoteIdentifier(parts[parts.length - 1])
|
||||
}
|
||||
|
||||
function stripTrailingSemicolon(sql: string): string {
|
||||
return sql.replace(/;\s*$/, '')
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,36 +0,0 @@
|
||||
import { describe, expect, it } from 'bun:test'
|
||||
import { handleBenchmarkApiFetch, hasBenchmarkApiHandler } from './mockBackend'
|
||||
|
||||
// `list_workers`'s client call is not faked, so its request really does leave as a relative
|
||||
// `/api/...` url that node's fetch cannot resolve. Without this route the tool throws instead
|
||||
// of answering.
|
||||
describe('benchmark API fetch handlers', () => {
|
||||
it('lists workers, the way list_workers reaches them', async () => {
|
||||
const url = '/api/workers/list?per_page=100'
|
||||
|
||||
expect(hasBenchmarkApiHandler(url)).toBe(true)
|
||||
const body = await handleBenchmarkApiFetch(url).json()
|
||||
|
||||
// The tool counts the list and maps over it, so it needs a bare array, not an envelope.
|
||||
expect(Array.isArray(body)).toBe(true)
|
||||
expect(body[0]).toMatchObject({ worker: expect.any(String), worker_group: expect.any(String) })
|
||||
})
|
||||
})
|
||||
|
||||
// A benchmark whose list calls an integration undocumented while its metadata endpoint
|
||||
// hands back authored notes teaches the model the flag means nothing.
|
||||
describe('benchmark hub integration list', () => {
|
||||
it('flags exactly the integrations whose metadata carries authored notes', async () => {
|
||||
const listed = (await handleBenchmarkApiFetch('/api/integrations/hub/list').json()) as Array<{
|
||||
name: string
|
||||
documented: boolean
|
||||
}>
|
||||
expect(listed.length).toBeGreaterThan(0)
|
||||
|
||||
for (const { name, documented } of listed) {
|
||||
const res = handleBenchmarkApiFetch(`/api/integrations/hub/${name}/meta`)
|
||||
const authored = res.status === 200 && !!((await res.json()) as { meta?: unknown }).meta
|
||||
expect(authored).toBe(documented)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1,175 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'bun:test'
|
||||
import {
|
||||
getBenchmarkCompletedJobResultMaybe,
|
||||
getBenchmarkDatatableSchema,
|
||||
listBenchmarkDatatables,
|
||||
registerBenchmarkWorkspaceRunnables,
|
||||
resetBenchmarkMockBackend,
|
||||
runBenchmarkDatatableSql,
|
||||
type BenchmarkWorkspaceRunnables
|
||||
} from './mockBackend'
|
||||
|
||||
const WORKSPACE = 'benchmark-datatable-ws'
|
||||
|
||||
// Mirrors the production `isDatatableNotConfiguredError` regex in
|
||||
// datatableTools.ts. The schema mock's "not configured" message MUST match it,
|
||||
// otherwise the not-configured mapping in get_datatable_table_schema is silently
|
||||
// untested.
|
||||
const NOT_CONFIGURED_RE = /datatable\s+\S+\s+not found/i
|
||||
|
||||
const SEED: BenchmarkWorkspaceRunnables = {
|
||||
datatables: [
|
||||
{
|
||||
datatable_name: 'main',
|
||||
schemas: {
|
||||
public: {
|
||||
orders: {
|
||||
columns: { id: 'int', total: 'numeric' },
|
||||
rows: [
|
||||
{ id: 1, total: 10 },
|
||||
{ id: 2, total: 20 }
|
||||
]
|
||||
},
|
||||
customers: {
|
||||
columns: { id: 'int', name: 'text' },
|
||||
rows: [{ id: 1, name: 'alice' }]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
beforeEach(() => resetBenchmarkMockBackend())
|
||||
afterEach(() => resetBenchmarkMockBackend())
|
||||
|
||||
describe('listBenchmarkDatatables', () => {
|
||||
it('returns null for a non-benchmark workspace (caller falls through to real backend)', () => {
|
||||
expect(listBenchmarkDatatables('unregistered')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns [] for a registered workspace with no datatables seed', () => {
|
||||
registerBenchmarkWorkspaceRunnables(WORKSPACE, {})
|
||||
expect(listBenchmarkDatatables(WORKSPACE)).toEqual([])
|
||||
})
|
||||
|
||||
it('projects seeded datatables to schema -> table names only (no columns)', () => {
|
||||
registerBenchmarkWorkspaceRunnables(WORKSPACE, SEED)
|
||||
expect(listBenchmarkDatatables(WORKSPACE)).toEqual([
|
||||
{ datatable_name: 'main', schemas: { public: ['orders', 'customers'] } }
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('getBenchmarkDatatableSchema', () => {
|
||||
beforeEach(() => registerBenchmarkWorkspaceRunnables(WORKSPACE, SEED))
|
||||
|
||||
it('returns the columns for a seeded table', () => {
|
||||
expect(
|
||||
getBenchmarkDatatableSchema({
|
||||
workspace: WORKSPACE,
|
||||
datatableName: 'main',
|
||||
schemaName: 'public',
|
||||
tableName: 'orders'
|
||||
})
|
||||
).toEqual({
|
||||
datatable_name: 'main',
|
||||
schema_name: 'public',
|
||||
table_name: 'orders',
|
||||
columns: { id: 'int', total: 'numeric' }
|
||||
})
|
||||
})
|
||||
|
||||
it('throws a not-configured error matching the production regex for an unknown datatable', () => {
|
||||
let error: Error | undefined
|
||||
try {
|
||||
getBenchmarkDatatableSchema({
|
||||
workspace: WORKSPACE,
|
||||
datatableName: 'ghost',
|
||||
schemaName: 'public',
|
||||
tableName: 'orders'
|
||||
})
|
||||
} catch (e) {
|
||||
error = e as Error
|
||||
}
|
||||
expect(error).toBeDefined()
|
||||
expect(error!.message).toMatch(NOT_CONFIGURED_RE)
|
||||
})
|
||||
|
||||
it('throws a table-not-found error that does NOT match the datatable-not-configured regex', () => {
|
||||
// The datatable IS configured; only the table is missing. Production maps
|
||||
// this to a generic "error getting schema", not the blocking message.
|
||||
let error: Error | undefined
|
||||
try {
|
||||
getBenchmarkDatatableSchema({
|
||||
workspace: WORKSPACE,
|
||||
datatableName: 'main',
|
||||
schemaName: 'public',
|
||||
tableName: 'ghost'
|
||||
})
|
||||
} catch (e) {
|
||||
error = e as Error
|
||||
}
|
||||
expect(error).toBeDefined()
|
||||
expect(error!.message).not.toMatch(NOT_CONFIGURED_RE)
|
||||
})
|
||||
})
|
||||
|
||||
describe('runBenchmarkDatatableSql + getBenchmarkCompletedJobResultMaybe', () => {
|
||||
beforeEach(() => registerBenchmarkWorkspaceRunnables(WORKSPACE, SEED))
|
||||
|
||||
function exec(sql: string): { success: boolean; completed: boolean; result: unknown } {
|
||||
const jobId = runBenchmarkDatatableSql({ workspace: WORKSPACE, datatableName: 'main', sql })
|
||||
return getBenchmarkCompletedJobResultMaybe({ workspace: WORKSPACE, id: jobId })
|
||||
}
|
||||
|
||||
it('returns the canned rows of the table named in a SELECT FROM clause', () => {
|
||||
expect(exec('SELECT * FROM customers')).toEqual({
|
||||
success: true,
|
||||
completed: true,
|
||||
result: [{ id: 1, name: 'alice' }]
|
||||
})
|
||||
})
|
||||
|
||||
it('falls back to the first seeded table when the SELECT references no known table', () => {
|
||||
expect(exec('select 1').result).toEqual([
|
||||
{ id: 1, total: 10 },
|
||||
{ id: 2, total: 20 }
|
||||
])
|
||||
})
|
||||
|
||||
it('returns [] success for DDL and DML statements without RETURNING', () => {
|
||||
expect(exec('CREATE TABLE foo (id int)').result).toEqual([])
|
||||
expect(exec('INSERT INTO orders VALUES (3, 30)').result).toEqual([])
|
||||
expect(exec('update orders set total = 0').result).toEqual([])
|
||||
})
|
||||
|
||||
it('reflects a write in a later SELECT, isolated from the shared seed', () => {
|
||||
exec('UPDATE orders SET total = 999 WHERE id = 1')
|
||||
expect((exec('SELECT * FROM orders').result as Record<string, unknown>[])).toContainEqual({
|
||||
id: 1,
|
||||
total: 999
|
||||
})
|
||||
// Registration deep-clones the seed, so the shared SEED const stays pristine.
|
||||
expect(SEED.datatables![0].schemas.public.orders.rows).toContainEqual({ id: 1, total: 10 })
|
||||
})
|
||||
|
||||
it('reflects a CREATE in list_datatables and get_datatable_table_schema', () => {
|
||||
exec('CREATE TABLE public.refunds (order_id int4, amount numeric)')
|
||||
expect(listBenchmarkDatatables(WORKSPACE)?.[0].schemas.public).toContain('refunds')
|
||||
expect(
|
||||
getBenchmarkDatatableSchema({
|
||||
workspace: WORKSPACE,
|
||||
datatableName: 'main',
|
||||
schemaName: 'public',
|
||||
tableName: 'refunds'
|
||||
}).columns
|
||||
).toEqual({ order_id: 'int4', amount: 'numeric' })
|
||||
})
|
||||
|
||||
it('throws for an unknown job id', () => {
|
||||
expect(() =>
|
||||
getBenchmarkCompletedJobResultMaybe({ workspace: WORKSPACE, id: 'does-not-exist' })
|
||||
).toThrow()
|
||||
})
|
||||
})
|
||||
@@ -1,116 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'bun:test'
|
||||
import {
|
||||
clearBenchmarkDrafts,
|
||||
getBenchmarkDraftForUser,
|
||||
getBenchmarkOwnDraft,
|
||||
listBenchmarkDrafts,
|
||||
resetBenchmarkMockBackend,
|
||||
seedBenchmarkDraft,
|
||||
updateBenchmarkDraft
|
||||
} from './mockBackend'
|
||||
|
||||
const WORKSPACE = 'benchmark-drafts-ws'
|
||||
|
||||
// Drives the in-memory stand-in for the per-user draft backend (`DraftService`)
|
||||
// that the global AI-chat eval round-trips its drafts through. Mirrors the
|
||||
// production-unit-test mock in
|
||||
// `frontend/src/lib/components/copilot/chat/global/core.test.ts`.
|
||||
describe('mockBackend drafts', () => {
|
||||
beforeEach(() => resetBenchmarkMockBackend())
|
||||
afterEach(() => resetBenchmarkMockBackend())
|
||||
|
||||
it('round-trips a saved draft through update / get / list', () => {
|
||||
const value = { summary: 'Greet a user', content: 'export async function main() {}' }
|
||||
const res = updateBenchmarkDraft({
|
||||
workspace: WORKSPACE,
|
||||
kind: 'script',
|
||||
path: 'f/evals/greet',
|
||||
requestBody: { value }
|
||||
})
|
||||
expect(res.status).toBe('saved')
|
||||
|
||||
expect(getBenchmarkDraftForUser({ workspace: WORKSPACE, kind: 'script', path: 'f/evals/greet' }).value).toEqual(
|
||||
value
|
||||
)
|
||||
|
||||
const rows = listBenchmarkDrafts(WORKSPACE)
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(rows[0]).toMatchObject({ kind: 'script', path: 'f/evals/greet', summary: 'Greet a user', draft_only: true })
|
||||
})
|
||||
|
||||
it('treats a null value as a delete', () => {
|
||||
updateBenchmarkDraft({
|
||||
workspace: WORKSPACE,
|
||||
kind: 'variable',
|
||||
path: 'f/evals/token',
|
||||
requestBody: { value: { summary: 'token' } }
|
||||
})
|
||||
updateBenchmarkDraft({
|
||||
workspace: WORKSPACE,
|
||||
kind: 'variable',
|
||||
path: 'f/evals/token',
|
||||
requestBody: { value: null }
|
||||
})
|
||||
|
||||
expect(listBenchmarkDrafts(WORKSPACE)).toHaveLength(0)
|
||||
expect(() => getBenchmarkDraftForUser({ workspace: WORKSPACE, kind: 'variable', path: 'f/evals/token' })).toThrow()
|
||||
})
|
||||
|
||||
it('returns null from getOwnDraft when no draft exists', () => {
|
||||
expect(
|
||||
getBenchmarkOwnDraft({ workspace: WORKSPACE, kind: 'trigger_schedule', path: 'u/evals/missing' })
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
// The global chat hydrates drawer-kind drafts (schedule/trigger/resource/variable)
|
||||
// through getOwnDraft — getDraftForUser rejects those kinds as private.
|
||||
it('hydrates a saved drawer-kind draft through getOwnDraft', () => {
|
||||
const value = { path: 'u/evals/nightly', schedule: '0 0 9 * * *' }
|
||||
updateBenchmarkDraft({
|
||||
workspace: WORKSPACE,
|
||||
kind: 'trigger_schedule',
|
||||
path: 'u/evals/nightly',
|
||||
requestBody: { value }
|
||||
})
|
||||
expect(
|
||||
getBenchmarkOwnDraft({ workspace: WORKSPACE, kind: 'trigger_schedule', path: 'u/evals/nightly' })?.value
|
||||
).toEqual(value)
|
||||
})
|
||||
|
||||
it('throws a 404-shaped error when no draft exists', () => {
|
||||
try {
|
||||
getBenchmarkDraftForUser({ workspace: WORKSPACE, kind: 'script', path: 'f/evals/missing' })
|
||||
throw new Error('expected a throw')
|
||||
} catch (e) {
|
||||
expect((e as { status?: number }).status).toBe(404)
|
||||
}
|
||||
})
|
||||
|
||||
it('seeds a draft as a backend row that a later edit overwrites', () => {
|
||||
seedBenchmarkDraft(WORKSPACE, 'script', 'f/evals/current', { content: 'seed' })
|
||||
expect(getBenchmarkDraftForUser({ workspace: WORKSPACE, kind: 'script', path: 'f/evals/current' }).value).toEqual({
|
||||
content: 'seed'
|
||||
})
|
||||
|
||||
// A model edit persists the same path and must win over the seed.
|
||||
updateBenchmarkDraft({
|
||||
workspace: WORKSPACE,
|
||||
kind: 'script',
|
||||
path: 'f/evals/current',
|
||||
requestBody: { value: { content: 'edited' } }
|
||||
})
|
||||
expect(getBenchmarkDraftForUser({ workspace: WORKSPACE, kind: 'script', path: 'f/evals/current' }).value).toEqual({
|
||||
content: 'edited'
|
||||
})
|
||||
})
|
||||
|
||||
it('clears only the targeted workspace', () => {
|
||||
seedBenchmarkDraft(WORKSPACE, 'script', 'f/a', { content: 'a' })
|
||||
seedBenchmarkDraft('other-ws', 'script', 'f/b', { content: 'b' })
|
||||
|
||||
clearBenchmarkDrafts(WORKSPACE)
|
||||
|
||||
expect(listBenchmarkDrafts(WORKSPACE)).toHaveLength(0)
|
||||
expect(listBenchmarkDrafts('other-ws')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@@ -8,6 +8,7 @@ import { fileURLToPath } from 'url'
|
||||
import { handleBenchmarkApiFetch, hasBenchmarkApiHandler } from './mockBackend'
|
||||
import { resolveWindmillBackendSettings } from '../../core/windmillBackendSettings'
|
||||
import { WindmillBackendClient } from './windmillBackend'
|
||||
import { realWorkspaceRoute } from './core/global/realWorkspace'
|
||||
|
||||
const FRONTEND_DIR = fileURLToPath(new URL('../../../frontend/', import.meta.url))
|
||||
|
||||
@@ -30,6 +31,13 @@ globalThis.fetch = (async (input: unknown, init?: RequestInit) => {
|
||||
if (typeof url === 'string' && hasBenchmarkApiHandler(url)) {
|
||||
return handleBenchmarkApiFetch(url, init)
|
||||
}
|
||||
// A global-mode case runs against a real workspace: send its calls there, as its user.
|
||||
const real = typeof url === 'string' ? realWorkspaceRoute(url) : undefined
|
||||
if (real) {
|
||||
const headers = new Headers(init?.headers)
|
||||
headers.set('Authorization', `Bearer ${real.token}`)
|
||||
return ORIGINAL_FETCH(real.url, { ...init, headers })
|
||||
}
|
||||
// The docs tools read the documentation bundled into the backend: hand them to the
|
||||
// benchmark's real backend, logged in like the AI proxy calls.
|
||||
if (typeof url === 'string' && url.startsWith('/api/docs/')) {
|
||||
@@ -119,60 +127,21 @@ vi.mock('$lib/components/apps/components/display/dbtable/metadata', async () =>
|
||||
vi.mock('$lib/gen', async () => {
|
||||
const actual = await vi.importActual<any>('$lib/gen')
|
||||
const {
|
||||
getBenchmarkAppByPath,
|
||||
getBenchmarkJob,
|
||||
getBenchmarkCompletedJobResultMaybe,
|
||||
listBenchmarkWorkers,
|
||||
listBenchmarkSchedules,
|
||||
getBenchmarkSchedule,
|
||||
listBenchmarkFolders,
|
||||
getBenchmarkFolder,
|
||||
getBenchmarkGroup,
|
||||
listBenchmarkGroups,
|
||||
getBenchmarkWorkspaceSettingsDocument,
|
||||
applyBenchmarkWorkspaceSettingsDocument,
|
||||
getBenchmarkDatatableSchema,
|
||||
getBenchmarkDatatableMigrationsStatus,
|
||||
createBenchmarkDatatableMigration,
|
||||
upsertBenchmarkDatatableMigration,
|
||||
runBenchmarkDatatableMigrations,
|
||||
rollbackBenchmarkDatatableMigration,
|
||||
getBenchmarkDraftForUser,
|
||||
getBenchmarkCompletedJob,
|
||||
getBenchmarkFlowByPath,
|
||||
getBenchmarkFlowAllResults,
|
||||
getBenchmarkJobLogs,
|
||||
getBenchmarkOwnDraft,
|
||||
getBenchmarkScriptByHash,
|
||||
getBenchmarkScriptByPath,
|
||||
getBenchmarkAiConfig,
|
||||
getBenchmarkResourceValue,
|
||||
getBenchmarkVariableByPath,
|
||||
hasBenchmarkWorkspace,
|
||||
getBenchmarkResource,
|
||||
listBenchmarkAiProviderResources,
|
||||
listBenchmarkPlainResources,
|
||||
listBenchmarkResourceTypeNames,
|
||||
queryBenchmarkResourceTypes,
|
||||
createBenchmarkResourceType,
|
||||
listBenchmarkApps,
|
||||
listBenchmarkDatatables,
|
||||
listBenchmarkDataMetrics,
|
||||
listBenchmarkDrafts,
|
||||
listBenchmarkDucklakes,
|
||||
listBenchmarkFlows,
|
||||
listBenchmarkJobs,
|
||||
listBenchmarkScripts,
|
||||
listBenchmarkVariables,
|
||||
createBenchmarkFolder,
|
||||
createBenchmarkHttpTrigger,
|
||||
createBenchmarkSchedule,
|
||||
previewBenchmarkSchedule,
|
||||
runBenchmarkDatatableSql,
|
||||
runBenchmarkFlowByPath,
|
||||
runBenchmarkFlowPreview,
|
||||
runBenchmarkScriptByPath,
|
||||
runBenchmarkScriptPreview,
|
||||
updateBenchmarkDraft
|
||||
runBenchmarkScriptPreview
|
||||
} = await import('./mockBackend')
|
||||
|
||||
function wrapService<T extends object>(target: T, overrides: Record<string, unknown>): T {
|
||||
@@ -188,104 +157,23 @@ vi.mock('$lib/gen', async () => {
|
||||
|
||||
return {
|
||||
...actual,
|
||||
DraftService: wrapService(actual.DraftService, {
|
||||
updateDraft: async (data: {
|
||||
workspace: string
|
||||
kind: any
|
||||
path: string
|
||||
requestBody?: { value?: unknown }
|
||||
}) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? updateBenchmarkDraft(data)
|
||||
: actual.DraftService.updateDraft(data),
|
||||
getDraftForUser: async (data: { workspace: string; kind: any; path: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? getBenchmarkDraftForUser(data)
|
||||
: actual.DraftService.getDraftForUser(data),
|
||||
getOwnDraft: async (data: { workspace: string; kind: any; path: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? getBenchmarkOwnDraft(data)
|
||||
: actual.DraftService.getOwnDraft(data),
|
||||
listDrafts: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? listBenchmarkDrafts(data.workspace)
|
||||
: actual.DraftService.listDrafts(data)
|
||||
}),
|
||||
FolderService: wrapService(actual.FolderService, {
|
||||
createFolder: async (data: { workspace: string; requestBody: { name: string } }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? createBenchmarkFolder(data.workspace, data.requestBody.name)
|
||||
: actual.FolderService.createFolder(data),
|
||||
listFolders: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? listBenchmarkFolders(data.workspace)
|
||||
: actual.FolderService.listFolders(data),
|
||||
getFolder: async (data: { workspace: string; name: string }) => {
|
||||
if (!hasBenchmarkWorkspace(data.workspace)) return actual.FolderService.getFolder(data)
|
||||
const folder = getBenchmarkFolder(data.workspace, data.name)
|
||||
if (!folder) throw new Error(`Folder "${data.name}" not found in benchmark workspace`)
|
||||
return folder
|
||||
}
|
||||
}),
|
||||
GroupService: wrapService(actual.GroupService, {
|
||||
listGroups: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? listBenchmarkGroups(data.workspace)
|
||||
: actual.GroupService.listGroups(data),
|
||||
getGroup: async (data: { workspace: string; name: string }) => {
|
||||
if (!hasBenchmarkWorkspace(data.workspace)) return actual.GroupService.getGroup(data)
|
||||
const group = getBenchmarkGroup(data.workspace, data.name)
|
||||
if (!group) throw new Error(`Group "${data.name}" not found in benchmark workspace`)
|
||||
return group
|
||||
}
|
||||
}),
|
||||
ScriptService: wrapService(actual.ScriptService, {
|
||||
listScripts: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? (listBenchmarkScripts(data.workspace) ?? [])
|
||||
: actual.ScriptService.listScripts(data),
|
||||
existsScriptByPath: async (data: { workspace: string; path: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? Boolean(getBenchmarkScriptByPath(data.workspace, data.path))
|
||||
: actual.ScriptService.existsScriptByPath(data),
|
||||
getScriptByPath: async (data: { workspace: string; path: string; getDraft?: boolean }) => {
|
||||
getScriptByPath: async (data: { workspace: string; path: string }) => {
|
||||
if (hasBenchmarkWorkspace(data.workspace)) {
|
||||
const script = getBenchmarkScriptByPath(data.workspace, data.path)
|
||||
// `getDraft` mirrors production's overlay: the row plus the caller's
|
||||
// draft and a `no_deployed` marker (draft-only item). The diff tool
|
||||
// reads through this shape — without it every draft looks absent.
|
||||
const draft = data.getDraft
|
||||
? getBenchmarkOwnDraft({ workspace: data.workspace, kind: 'script', path: data.path })
|
||||
: null
|
||||
if (!script) {
|
||||
if (data.getDraft && draft) {
|
||||
return {
|
||||
...(draft.value as Record<string, unknown>),
|
||||
path: data.path,
|
||||
draft: draft.value,
|
||||
no_deployed: true
|
||||
}
|
||||
}
|
||||
throw Object.assign(
|
||||
new Error(`Script "${data.path}" not found in benchmark workspace`),
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
return data.getDraft
|
||||
? { ...script, draft: draft?.value ?? undefined, no_deployed: false }
|
||||
: script
|
||||
}
|
||||
return actual.ScriptService.getScriptByPath(data)
|
||||
},
|
||||
getScriptByPathWithDraft: async (data: { workspace: string; path: string }) => {
|
||||
if (hasBenchmarkWorkspace(data.workspace)) {
|
||||
const script = getBenchmarkScriptByPath(data.workspace, data.path)
|
||||
if (!script) {
|
||||
throw new Error(`Script "${data.path}" not found in benchmark workspace`)
|
||||
}
|
||||
return script
|
||||
}
|
||||
return actual.ScriptService.getScriptByPathWithDraft(data)
|
||||
return actual.ScriptService.getScriptByPath(data)
|
||||
},
|
||||
getScriptByHash: async (data: { workspace: string; hash: string }) => {
|
||||
if (hasBenchmarkWorkspace(data.workspace)) {
|
||||
@@ -303,56 +191,18 @@ vi.mock('$lib/gen', async () => {
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? (listBenchmarkFlows(data.workspace) ?? [])
|
||||
: actual.FlowService.listFlows(data),
|
||||
existsFlowByPath: async (data: { workspace: string; path: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? Boolean(getBenchmarkFlowByPath(data.workspace, data.path))
|
||||
: actual.FlowService.existsFlowByPath(data),
|
||||
getFlowByPath: async (data: { workspace: string; path: string; getDraft?: boolean }) => {
|
||||
getFlowByPath: async (data: { workspace: string; path: string }) => {
|
||||
if (hasBenchmarkWorkspace(data.workspace)) {
|
||||
const flow = getBenchmarkFlowByPath(data.workspace, data.path)
|
||||
// Mirror production's `getDraft` overlay (see getScriptByPath above).
|
||||
const draft = data.getDraft
|
||||
? getBenchmarkOwnDraft({ workspace: data.workspace, kind: 'flow', path: data.path })
|
||||
: null
|
||||
if (!flow) {
|
||||
if (data.getDraft && draft) {
|
||||
return {
|
||||
...(draft.value as Record<string, unknown>),
|
||||
path: data.path,
|
||||
draft: draft.value,
|
||||
no_deployed: true
|
||||
}
|
||||
}
|
||||
throw Object.assign(
|
||||
new Error(`Flow "${data.path}" not found in benchmark workspace`),
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
return data.getDraft
|
||||
? { ...flow, draft: draft?.value ?? undefined, no_deployed: false }
|
||||
: flow
|
||||
}
|
||||
return actual.FlowService.getFlowByPath(data)
|
||||
},
|
||||
getFlowByPathWithDraft: async (data: { workspace: string; path: string }) => {
|
||||
if (hasBenchmarkWorkspace(data.workspace)) {
|
||||
const flow = getBenchmarkFlowByPath(data.workspace, data.path)
|
||||
if (!flow) {
|
||||
throw new Error(`Flow "${data.path}" not found in benchmark workspace`)
|
||||
}
|
||||
return flow
|
||||
}
|
||||
return actual.FlowService.getFlowByPathWithDraft(data)
|
||||
},
|
||||
getFlowLatestVersion: async (data: { workspace: string; path: string }) => {
|
||||
if (hasBenchmarkWorkspace(data.workspace)) {
|
||||
const flow = getBenchmarkFlowByPath(data.workspace, data.path)
|
||||
if (!flow) {
|
||||
throw new Error(`Flow "${data.path}" not found in benchmark workspace`)
|
||||
}
|
||||
return { id: 1 }
|
||||
}
|
||||
return actual.FlowService.getFlowLatestVersion(data)
|
||||
return actual.FlowService.getFlowByPath(data)
|
||||
}
|
||||
}),
|
||||
JobService: wrapService(actual.JobService, {
|
||||
@@ -364,43 +214,16 @@ vi.mock('$lib/gen', async () => {
|
||||
args?: Record<string, unknown>
|
||||
path?: string
|
||||
}
|
||||
}) => {
|
||||
if (!hasBenchmarkWorkspace(data.workspace)) {
|
||||
return actual.JobService.runScriptPreview(data)
|
||||
}
|
||||
const requestBody = data.requestBody ?? {}
|
||||
const database = requestBody.args?.database
|
||||
// Datatable SQL runs as a `postgresql` preview against `datatable://<name>`.
|
||||
// Execute it through the canned-SQL mock instead of linting it as a script.
|
||||
if (
|
||||
requestBody.language === 'postgresql' &&
|
||||
typeof database === 'string' &&
|
||||
database.startsWith('datatable://')
|
||||
) {
|
||||
return runBenchmarkDatatableSql({
|
||||
workspace: data.workspace,
|
||||
datatableName: database.slice('datatable://'.length),
|
||||
sql: requestBody.content ?? ''
|
||||
})
|
||||
}
|
||||
return runBenchmarkScriptPreview({ workspace: data.workspace, requestBody })
|
||||
},
|
||||
runScriptByPath: async (data: {
|
||||
workspace: string
|
||||
path: string
|
||||
requestBody?: Record<string, unknown>
|
||||
}) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? runBenchmarkScriptByPath({
|
||||
? runBenchmarkScriptPreview({
|
||||
workspace: data.workspace,
|
||||
path: data.path,
|
||||
args: data.requestBody
|
||||
requestBody: data.requestBody ?? {}
|
||||
})
|
||||
: actual.JobService.runScriptByPath(data),
|
||||
: actual.JobService.runScriptPreview(data),
|
||||
runFlowPreview: async (data: {
|
||||
workspace: string
|
||||
memoryId?: string
|
||||
requestBody?: { path?: string; value?: { chat_input_enabled?: boolean }; args?: unknown }
|
||||
requestBody?: { path?: string; args?: unknown }
|
||||
}) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? runBenchmarkFlowPreview(data)
|
||||
@@ -426,24 +249,10 @@ vi.mock('$lib/gen', async () => {
|
||||
return job
|
||||
}
|
||||
return actual.JobService.getJob(data)
|
||||
},
|
||||
getCompletedJobResultMaybe: async (data: { workspace: string; id: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? getBenchmarkCompletedJobResultMaybe({ workspace: data.workspace, id: data.id })
|
||||
: actual.JobService.getCompletedJobResultMaybe(data),
|
||||
listJobs: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? (listBenchmarkJobs(data.workspace) ?? [])
|
||||
: actual.JobService.listJobs(data),
|
||||
getJobLogs: async (data: { workspace: string; id: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? getBenchmarkJobLogs(data.workspace, data.id)
|
||||
: actual.JobService.getJobLogs(data),
|
||||
getFlowAllResults: async (data: { workspace: string; id: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? getBenchmarkFlowAllResults(data.workspace, data.id)
|
||||
: actual.JobService.getFlowAllResults(data)
|
||||
}
|
||||
}),
|
||||
// A benchmark workspace holds no resources and no AI settings: answer as an empty
|
||||
// workspace would, rather than send its temp-directory id to the real backend.
|
||||
WorkspaceService: wrapService(actual.WorkspaceService, {
|
||||
getWorkspaceSettingsDocument: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
@@ -454,77 +263,13 @@ vi.mock('$lib/gen', async () => {
|
||||
? applyBenchmarkWorkspaceSettingsDocument(data)
|
||||
: actual.WorkspaceService.applyWorkspaceSettingsDocument(data),
|
||||
getCopilotInfo: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? (getBenchmarkAiConfig(data.workspace) ?? {})
|
||||
: actual.WorkspaceService.getCopilotInfo(data),
|
||||
listDataTableTables: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? (listBenchmarkDatatables(data.workspace) ?? [])
|
||||
: actual.WorkspaceService.listDataTableTables(data),
|
||||
listDucklakes: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? (listBenchmarkDucklakes(data.workspace) ?? [])
|
||||
: actual.WorkspaceService.listDucklakes(data),
|
||||
getDataTableTableSchema: async (data: {
|
||||
workspace: string
|
||||
datatableName: string
|
||||
schemaName: string
|
||||
tableName: string
|
||||
}) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? getBenchmarkDatatableSchema({
|
||||
workspace: data.workspace,
|
||||
datatableName: data.datatableName,
|
||||
schemaName: data.schemaName,
|
||||
tableName: data.tableName
|
||||
})
|
||||
: actual.WorkspaceService.getDataTableTableSchema(data),
|
||||
getDatatableMigrationsStatus: async (data: any) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? getBenchmarkDatatableMigrationsStatus(data)
|
||||
: actual.WorkspaceService.getDatatableMigrationsStatus(data),
|
||||
createDatatableMigration: async (data: any) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? createBenchmarkDatatableMigration(data)
|
||||
: actual.WorkspaceService.createDatatableMigration(data),
|
||||
upsertDatatableMigration: async (data: any) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? upsertBenchmarkDatatableMigration(data)
|
||||
: actual.WorkspaceService.upsertDatatableMigration(data),
|
||||
runDatatableMigrations: async (data: any) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? runBenchmarkDatatableMigrations(data)
|
||||
: actual.WorkspaceService.runDatatableMigrations(data),
|
||||
rollbackDatatableMigrations: async (data: any) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? rollbackBenchmarkDatatableMigration(data)
|
||||
: actual.WorkspaceService.rollbackDatatableMigrations(data)
|
||||
}),
|
||||
DataMetricService: wrapService(actual.DataMetricService, {
|
||||
listDataMetrics: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? { metrics: listBenchmarkDataMetrics(data.workspace) ?? [] }
|
||||
: actual.DataMetricService.listDataMetrics(data)
|
||||
hasBenchmarkWorkspace(data.workspace) ? {} : actual.WorkspaceService.getCopilotInfo(data)
|
||||
}),
|
||||
WorkerService: wrapService(actual.WorkerService, {
|
||||
listWorkers: async (data: Record<string, unknown>) =>
|
||||
listBenchmarkWorkers() ?? actual.WorkerService.listWorkers(data)
|
||||
}),
|
||||
ScheduleService: wrapService(actual.ScheduleService, {
|
||||
existsSchedule: async (data: { workspace: string; path: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace) ? false : actual.ScheduleService.existsSchedule(data),
|
||||
listSchedules: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? listBenchmarkSchedules(data.workspace)
|
||||
: actual.ScheduleService.listSchedules(data),
|
||||
getSchedule: async (data: { workspace: string; path: string }) => {
|
||||
if (hasBenchmarkWorkspace(data.workspace)) {
|
||||
const schedule = getBenchmarkSchedule(data.workspace, data.path)
|
||||
if (schedule) return schedule
|
||||
throw new Error(`Schedule "${data.path}" not found in benchmark workspace`)
|
||||
}
|
||||
return actual.ScheduleService.getSchedule(data)
|
||||
},
|
||||
previewSchedule: async (data: { requestBody?: Record<string, unknown> }) =>
|
||||
previewBenchmarkSchedule(data),
|
||||
createSchedule: async (data: { workspace: string; requestBody: Record<string, unknown> }) =>
|
||||
@@ -533,254 +278,27 @@ vi.mock('$lib/gen', async () => {
|
||||
: actual.ScheduleService.createSchedule(data)
|
||||
}),
|
||||
ResourceService: wrapService(actual.ResourceService, {
|
||||
existsResource: async (data: { workspace: string; path: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? Boolean(getBenchmarkResourceValue(data.workspace, data.path))
|
||||
: actual.ResourceService.existsResource(data),
|
||||
listResource: async (data: { workspace: string; resourceType?: string }) => {
|
||||
if (!hasBenchmarkWorkspace(data.workspace)) {
|
||||
return actual.ResourceService.listResource(data)
|
||||
}
|
||||
const seeded = [
|
||||
...(listBenchmarkAiProviderResources(data.workspace) ?? []),
|
||||
...(listBenchmarkPlainResources(data.workspace) ?? [])
|
||||
]
|
||||
const wanted = data.resourceType?.split(',')
|
||||
return wanted ? seeded.filter((r) => wanted.includes(r.resource_type)) : seeded
|
||||
},
|
||||
listResource: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace) ? [] : actual.ResourceService.listResource(data),
|
||||
getResource: async (data: { workspace: string; path: string }) => {
|
||||
if (hasBenchmarkWorkspace(data.workspace)) {
|
||||
const resource = getBenchmarkResource(data.workspace, data.path)
|
||||
if (!resource) {
|
||||
throw new Error(`Resource "${data.path}" not found in benchmark workspace`)
|
||||
}
|
||||
return resource
|
||||
throw new Error(`Resource "${data.path}" not found in benchmark workspace`)
|
||||
}
|
||||
return actual.ResourceService.getResource(data)
|
||||
},
|
||||
getResourceValue: async (data: { workspace: string; path: string }) => {
|
||||
if (!hasBenchmarkWorkspace(data.workspace)) {
|
||||
return actual.ResourceService.getResourceValue(data)
|
||||
}
|
||||
const value = getBenchmarkResourceValue(data.workspace, data.path)
|
||||
if (!value) {
|
||||
throw new Error(`Resource "${data.path}" not found in benchmark workspace`)
|
||||
}
|
||||
return value
|
||||
},
|
||||
queryResourceTypes: async (data: { workspace: string; text: string; limit?: number }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? queryBenchmarkResourceTypes(data.workspace, data.text, data.limit)
|
||||
? queryBenchmarkResourceTypes(data.text, data.limit)
|
||||
: actual.ResourceService.queryResourceTypes(data),
|
||||
listResourceTypeNames: async (data: { workspace: string }) =>
|
||||
listBenchmarkResourceTypeNames(data.workspace) ??
|
||||
actual.ResourceService.listResourceTypeNames(data),
|
||||
createResourceType: async (data: {
|
||||
workspace: string
|
||||
requestBody: { name: string; schema?: unknown; description?: string }
|
||||
}) => {
|
||||
if (!hasBenchmarkWorkspace(data.workspace)) {
|
||||
return actual.ResourceService.createResourceType(data)
|
||||
}
|
||||
createBenchmarkResourceType(data.workspace, data.requestBody)
|
||||
return `resource_type ${data.requestBody.name} created`
|
||||
}
|
||||
}),
|
||||
VariableService: wrapService(actual.VariableService, {
|
||||
existsVariable: async (data: { workspace: string; path: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? Boolean(getBenchmarkVariableByPath(data.workspace, data.path))
|
||||
: actual.VariableService.existsVariable(data),
|
||||
listVariable: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? (listBenchmarkVariables(data.workspace) ?? [])
|
||||
: actual.VariableService.listVariable(data),
|
||||
getVariable: async (data: {
|
||||
workspace: string
|
||||
path: string
|
||||
decryptSecret?: boolean
|
||||
}) => {
|
||||
if (hasBenchmarkWorkspace(data.workspace)) {
|
||||
const variable = getBenchmarkVariableByPath(
|
||||
data.workspace,
|
||||
data.path,
|
||||
data.decryptSecret ?? true
|
||||
)
|
||||
if (!variable) {
|
||||
throw new Error(`Variable "${data.path}" not found in benchmark workspace`)
|
||||
}
|
||||
return variable
|
||||
}
|
||||
return actual.VariableService.getVariable(data)
|
||||
}
|
||||
}),
|
||||
AppService: wrapService(actual.AppService, {
|
||||
existsApp: async (data: { workspace: string; path: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? Boolean(getBenchmarkAppByPath(data.workspace, data.path))
|
||||
: actual.AppService.existsApp(data),
|
||||
listApps: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? (listBenchmarkApps(data.workspace) ?? [])
|
||||
: actual.AppService.listApps(data),
|
||||
getAppByPath: async (data: {
|
||||
workspace: string
|
||||
path: string
|
||||
getDraft?: boolean
|
||||
rawApp?: boolean
|
||||
}) => {
|
||||
if (hasBenchmarkWorkspace(data.workspace)) {
|
||||
const app = getBenchmarkAppByPath(data.workspace, data.path)
|
||||
// Mirror production's `getDraft` overlay (see getScriptByPath above).
|
||||
// Benchmark app drafts live under the raw_app kind.
|
||||
const draft = data.getDraft
|
||||
? getBenchmarkOwnDraft({ workspace: data.workspace, kind: 'raw_app', path: data.path })
|
||||
: null
|
||||
if (!app) {
|
||||
if (data.getDraft && draft) {
|
||||
return {
|
||||
...(draft.value as Record<string, unknown>),
|
||||
path: data.path,
|
||||
raw_app: true,
|
||||
draft: draft.value,
|
||||
no_deployed: true
|
||||
}
|
||||
}
|
||||
throw Object.assign(
|
||||
new Error(`App "${data.path}" not found in benchmark workspace`),
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
return data.getDraft
|
||||
? { ...app, draft: draft?.value ?? undefined, no_deployed: false }
|
||||
: app
|
||||
}
|
||||
return actual.AppService.getAppByPath(data)
|
||||
}
|
||||
actual.ResourceService.listResourceTypeNames(data)
|
||||
}),
|
||||
HttpTriggerService: wrapService(actual.HttpTriggerService, {
|
||||
existsHttpTrigger: async (data: { workspace: string; path: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace) ? false : actual.HttpTriggerService.existsHttpTrigger(data),
|
||||
listHttpTriggers: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace) ? [] : actual.HttpTriggerService.listHttpTriggers(data),
|
||||
getHttpTrigger: async (data: { workspace: string; path: string }) => {
|
||||
if (hasBenchmarkWorkspace(data.workspace)) {
|
||||
throw new Error(`HTTP trigger "${data.path}" not found in benchmark workspace`)
|
||||
}
|
||||
return actual.HttpTriggerService.getHttpTrigger(data)
|
||||
},
|
||||
createHttpTrigger: async (data: { workspace: string; requestBody: Record<string, unknown> }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? createBenchmarkHttpTrigger(data)
|
||||
: actual.HttpTriggerService.createHttpTrigger(data)
|
||||
}),
|
||||
WebsocketTriggerService: wrapService(actual.WebsocketTriggerService, {
|
||||
existsWebsocketTrigger: async (data: { workspace: string; path: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? false
|
||||
: actual.WebsocketTriggerService.existsWebsocketTrigger(data),
|
||||
listWebsocketTriggers: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? []
|
||||
: actual.WebsocketTriggerService.listWebsocketTriggers(data),
|
||||
getWebsocketTrigger: async (data: { workspace: string; path: string }) => {
|
||||
if (hasBenchmarkWorkspace(data.workspace)) {
|
||||
throw new Error(`Websocket trigger "${data.path}" not found in benchmark workspace`)
|
||||
}
|
||||
return actual.WebsocketTriggerService.getWebsocketTrigger(data)
|
||||
}
|
||||
}),
|
||||
KafkaTriggerService: wrapService(actual.KafkaTriggerService, {
|
||||
existsKafkaTrigger: async (data: { workspace: string; path: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? false
|
||||
: actual.KafkaTriggerService.existsKafkaTrigger(data),
|
||||
listKafkaTriggers: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace) ? [] : actual.KafkaTriggerService.listKafkaTriggers(data),
|
||||
getKafkaTrigger: async (data: { workspace: string; path: string }) => {
|
||||
if (hasBenchmarkWorkspace(data.workspace)) {
|
||||
throw new Error(`Kafka trigger "${data.path}" not found in benchmark workspace`)
|
||||
}
|
||||
return actual.KafkaTriggerService.getKafkaTrigger(data)
|
||||
}
|
||||
}),
|
||||
NatsTriggerService: wrapService(actual.NatsTriggerService, {
|
||||
existsNatsTrigger: async (data: { workspace: string; path: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace) ? false : actual.NatsTriggerService.existsNatsTrigger(data),
|
||||
listNatsTriggers: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace) ? [] : actual.NatsTriggerService.listNatsTriggers(data),
|
||||
getNatsTrigger: async (data: { workspace: string; path: string }) => {
|
||||
if (hasBenchmarkWorkspace(data.workspace)) {
|
||||
throw new Error(`NATS trigger "${data.path}" not found in benchmark workspace`)
|
||||
}
|
||||
return actual.NatsTriggerService.getNatsTrigger(data)
|
||||
}
|
||||
}),
|
||||
PostgresTriggerService: wrapService(actual.PostgresTriggerService, {
|
||||
existsPostgresTrigger: async (data: { workspace: string; path: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? false
|
||||
: actual.PostgresTriggerService.existsPostgresTrigger(data),
|
||||
listPostgresTriggers: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? []
|
||||
: actual.PostgresTriggerService.listPostgresTriggers(data),
|
||||
getPostgresTrigger: async (data: { workspace: string; path: string }) => {
|
||||
if (hasBenchmarkWorkspace(data.workspace)) {
|
||||
throw new Error(`Postgres trigger "${data.path}" not found in benchmark workspace`)
|
||||
}
|
||||
return actual.PostgresTriggerService.getPostgresTrigger(data)
|
||||
}
|
||||
}),
|
||||
MqttTriggerService: wrapService(actual.MqttTriggerService, {
|
||||
existsMqttTrigger: async (data: { workspace: string; path: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace) ? false : actual.MqttTriggerService.existsMqttTrigger(data),
|
||||
listMqttTriggers: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace) ? [] : actual.MqttTriggerService.listMqttTriggers(data),
|
||||
getMqttTrigger: async (data: { workspace: string; path: string }) => {
|
||||
if (hasBenchmarkWorkspace(data.workspace)) {
|
||||
throw new Error(`MQTT trigger "${data.path}" not found in benchmark workspace`)
|
||||
}
|
||||
return actual.MqttTriggerService.getMqttTrigger(data)
|
||||
}
|
||||
}),
|
||||
SqsTriggerService: wrapService(actual.SqsTriggerService, {
|
||||
existsSqsTrigger: async (data: { workspace: string; path: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace) ? false : actual.SqsTriggerService.existsSqsTrigger(data),
|
||||
listSqsTriggers: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace) ? [] : actual.SqsTriggerService.listSqsTriggers(data),
|
||||
getSqsTrigger: async (data: { workspace: string; path: string }) => {
|
||||
if (hasBenchmarkWorkspace(data.workspace)) {
|
||||
throw new Error(`SQS trigger "${data.path}" not found in benchmark workspace`)
|
||||
}
|
||||
return actual.SqsTriggerService.getSqsTrigger(data)
|
||||
}
|
||||
}),
|
||||
GcpTriggerService: wrapService(actual.GcpTriggerService, {
|
||||
existsGcpTrigger: async (data: { workspace: string; path: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace) ? false : actual.GcpTriggerService.existsGcpTrigger(data),
|
||||
listGcpTriggers: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace) ? [] : actual.GcpTriggerService.listGcpTriggers(data),
|
||||
getGcpTrigger: async (data: { workspace: string; path: string }) => {
|
||||
if (hasBenchmarkWorkspace(data.workspace)) {
|
||||
throw new Error(`GCP trigger "${data.path}" not found in benchmark workspace`)
|
||||
}
|
||||
return actual.GcpTriggerService.getGcpTrigger(data)
|
||||
}
|
||||
}),
|
||||
AzureTriggerService: wrapService(actual.AzureTriggerService, {
|
||||
existsAzureTrigger: async (data: { workspace: string; path: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? false
|
||||
: actual.AzureTriggerService.existsAzureTrigger(data),
|
||||
listAzureTriggers: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace) ? [] : actual.AzureTriggerService.listAzureTriggers(data),
|
||||
getAzureTrigger: async (data: { workspace: string; path: string }) => {
|
||||
if (hasBenchmarkWorkspace(data.workspace)) {
|
||||
throw new Error(`Azure trigger "${data.path}" not found in benchmark workspace`)
|
||||
}
|
||||
return actual.AzureTriggerService.getAzureTrigger(data)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1989,6 +1989,153 @@
|
||||
- does not misuse `-- materialize` for the S3 Parquet export (materialize is DuckLake-only; the S3 output is written by the script body, e.g. a DuckDB COPY or an SDK write)
|
||||
- leaves all three nodes as AI drafts without deploying or saving
|
||||
|
||||
- id: global-pipeline-run-orders-daily
|
||||
prompt: |-
|
||||
Our raw order exports land as CSV files under `raw/orders/` in the workspace
|
||||
object storage. Build a data pipeline in the `shop` folder: one step that loads
|
||||
all of them into a DuckLake table called `orders`, and a second step that builds
|
||||
an `orders_daily` table with the number of orders and the total revenue for each
|
||||
day. The daily table should rebuild by itself whenever `orders` is refreshed.
|
||||
Keep everything as drafts, don't deploy.
|
||||
initial: ai_evals/fixtures/frontend/global/initial/pipeline_orders_storage.json
|
||||
runtime:
|
||||
maxTurns: 16
|
||||
validate:
|
||||
draftCountAtLeast: 2
|
||||
forbiddenDrafts:
|
||||
- type: flow
|
||||
pathStartsWith: f/shop/
|
||||
# The harness deploys the drafted nodes, runs the ones nothing upstream feeds, and lets
|
||||
# the asset triggers run the rest: the rollup only fills if its `on` wiring is right.
|
||||
pipelineRun:
|
||||
folder: shop
|
||||
# Only the ingest starts the pipeline; the rollup has to be reached by its trigger.
|
||||
maxRoots: 1
|
||||
queries:
|
||||
- name: orders holds every exported order
|
||||
sql: SELECT count(*) AS n, sum(amount) AS revenue FROM dl.orders
|
||||
includesValues: [6, 97.5]
|
||||
- name: orders_daily has one row per day with its count and revenue
|
||||
sql: SELECT * FROM dl.orders_daily
|
||||
rowCount: 3
|
||||
includesValues: [2, 25, 3, 32.5, 1, 40]
|
||||
toolExpect:
|
||||
requiredToolsUsed:
|
||||
- write_script
|
||||
forbiddenToolsUsed:
|
||||
- write_flow
|
||||
- deploy_workspace_item
|
||||
- delete_workspace_item
|
||||
judgeChecklist:
|
||||
# Pipeline nodes are declarative: `-- on <ref>` binds inputs/triggers and
|
||||
# `-- materialize ducklake://<table>` is a managed write whose body is a bare SELECT.
|
||||
# A read of a DuckLake table inside a pipeline node also derives its trigger, so an
|
||||
# explicit `-- on ducklake://main/orders` is good practice but not required.
|
||||
- builds the pipeline as two pipeline-annotated scripts in f/shop (not a flow)
|
||||
- the first step reads the CSV files under raw/orders/ from the workspace's default storage and materializes them into the DuckLake table `orders`
|
||||
- the second step reads `orders` and materializes `orders_daily` with a per-day order count and revenue total
|
||||
- the second step is wired to run when `orders` is produced
|
||||
- leaves both as drafts without deploying
|
||||
|
||||
- id: global-pipeline-run-tables-named-after-steps
|
||||
prompt: |-
|
||||
Our raw order exports land as CSV files under `raw/orders/` in the workspace
|
||||
object storage. Build a data pipeline in the `shop` folder with two steps:
|
||||
`orders`, which loads all of them into a DuckLake table, and `orders_daily`,
|
||||
which turns that into the number of orders and the total revenue for each day.
|
||||
Each table should just be named after the step that builds it, and the daily
|
||||
one should rebuild by itself whenever orders are refreshed. Keep everything as
|
||||
drafts, don't deploy.
|
||||
initial: ai_evals/fixtures/frontend/global/initial/pipeline_orders_storage.json
|
||||
runtime:
|
||||
maxTurns: 16
|
||||
validate:
|
||||
draftCountAtLeast: 2
|
||||
requiredDrafts:
|
||||
- type: script
|
||||
path: f/shop/orders
|
||||
- type: script
|
||||
path: f/shop/orders_daily
|
||||
forbiddenDrafts:
|
||||
- type: flow
|
||||
pathStartsWith: f/shop/
|
||||
# A `materialize` naming no table writes the table named after its script, so
|
||||
# `f/shop/orders` writes `ducklake://main/orders` whichever form the node uses.
|
||||
pipelineRun:
|
||||
folder: shop
|
||||
maxRoots: 1
|
||||
queries:
|
||||
- name: orders holds every exported order
|
||||
sql: SELECT count(*) AS n, sum(amount) AS revenue FROM dl.orders
|
||||
includesValues: [6, 97.5]
|
||||
- name: orders_daily has one row per day with its count and revenue
|
||||
sql: SELECT * FROM dl.orders_daily
|
||||
rowCount: 3
|
||||
includesValues: [2, 25, 3, 32.5, 1, 40]
|
||||
toolExpect:
|
||||
requiredToolsUsed:
|
||||
- write_script
|
||||
forbiddenToolsUsed:
|
||||
- write_flow
|
||||
- deploy_workspace_item
|
||||
- delete_workspace_item
|
||||
judgeChecklist:
|
||||
# A `-- materialize` that names no table writes `ducklake://main/<script name>`, so a
|
||||
# bare `-- materialize` on f/shop/orders is as correct as `-- materialize ducklake://main/orders`.
|
||||
- builds the pipeline as two pipeline-annotated scripts, f/shop/orders and f/shop/orders_daily (not a flow)
|
||||
- each step materializes a DuckLake table named after the step, either by a bare `-- materialize` or by naming that table explicitly
|
||||
- orders_daily reads the orders table and computes a per-day order count and revenue total
|
||||
- orders_daily is wired to run when the orders table is produced
|
||||
- leaves both as drafts without deploying
|
||||
|
||||
- id: global-session-pipeline-run-orders-daily
|
||||
prompt: |-
|
||||
Our raw order exports land as CSV files under `raw/orders/` in the workspace
|
||||
object storage. Build a data pipeline in the `shop` folder: one step that loads
|
||||
all of them into a DuckLake table called `orders`, and a second step that builds
|
||||
an `orders_daily` table with the number of orders and the total revenue for each
|
||||
day. The daily table should rebuild by itself whenever `orders` is refreshed.
|
||||
Don't deploy anything, I'll review it first.
|
||||
initial: ai_evals/fixtures/frontend/global/initial/pipeline_orders_storage.json
|
||||
runtime:
|
||||
sessionChat: true
|
||||
maxTurns: 18
|
||||
validate:
|
||||
draftCountAtLeast: 2
|
||||
forbiddenDrafts:
|
||||
- type: flow
|
||||
pathStartsWith: f/shop/
|
||||
pipelineRun:
|
||||
folder: shop
|
||||
maxRoots: 1
|
||||
queries:
|
||||
- name: orders holds every exported order
|
||||
sql: SELECT count(*) AS n, sum(amount) AS revenue FROM dl.orders
|
||||
includesValues: [6, 97.5]
|
||||
- name: orders_daily has one row per day with its count and revenue
|
||||
sql: SELECT * FROM dl.orders_daily
|
||||
rowCount: 3
|
||||
includesValues: [2, 25, 3, 32.5, 1, 40]
|
||||
toolExpect:
|
||||
# In a session, pipeline nodes are built in the folder's pipeline editor.
|
||||
requiredToolsUsed:
|
||||
- open_preview
|
||||
- build_pipeline_node
|
||||
forbiddenToolsUsed:
|
||||
- write_flow
|
||||
- deploy_workspace_item
|
||||
- delete_workspace_item
|
||||
judgeChecklist:
|
||||
# Pipeline nodes are declarative: `-- on <ref>` binds inputs/triggers and
|
||||
# `-- materialize ducklake://<table>` is a managed write whose body is a bare SELECT.
|
||||
# A read of a DuckLake table inside a pipeline node also derives its trigger, so an
|
||||
# explicit `-- on ducklake://main/orders` is good practice but not required.
|
||||
- builds the pipeline as two pipeline nodes in f/shop (not a flow)
|
||||
- the first node reads the CSV files under raw/orders/ from the workspace's default storage and materializes them into the DuckLake table `orders`
|
||||
- the second node reads `orders` and materializes `orders_daily` with a per-day order count and revenue total
|
||||
- the second node is wired to run when `orders` is produced
|
||||
- leaves both as drafts without deploying
|
||||
|
||||
- id: global-path5-create-folder-then-draft
|
||||
prompt: |-
|
||||
Create a new shared folder called "analytics" for our data work, then draft a
|
||||
|
||||
@@ -117,6 +117,7 @@ async function runCaseAttempts<TInitial, TExpected, TActual>(input: {
|
||||
attempt,
|
||||
runs: input.runs,
|
||||
verbose: input.verbose,
|
||||
executionOnly: input.executionOnly,
|
||||
onAssistantMessageStart: input.verbose && surface
|
||||
? () =>
|
||||
input.onProgress?.({
|
||||
|
||||
@@ -152,6 +152,56 @@ export interface GlobalValidationSpec {
|
||||
path: string;
|
||||
triggerKind?: string;
|
||||
}>;
|
||||
/**
|
||||
* Deploy the pipeline nodes drafted under `f/<folder>/` to the case's workspace once the chat
|
||||
* is over, run the ones nothing upstream feeds, let the asset triggers run the rest, then
|
||||
* query the DuckLake. Needs `objectStorage` in the fixture and an eval backend that runs
|
||||
* DuckDB jobs; without `WMILL_AI_EVAL_S3_ENDPOINT` the run is skipped (README).
|
||||
*/
|
||||
pipelineRun?: PipelineRunSpec;
|
||||
}
|
||||
|
||||
export interface PipelineRunSpec {
|
||||
folder: string;
|
||||
/**
|
||||
* How many nodes the pipeline may start from. A node no recorded read or trigger ties to
|
||||
* an upstream one is started directly, and so passes whatever its `on` says; capping the
|
||||
* roots fails that, e.g. a read the asset parser records under another path.
|
||||
*/
|
||||
maxRoots?: number;
|
||||
timeoutSeconds?: number;
|
||||
queries?: PipelineRunQuery[];
|
||||
}
|
||||
|
||||
/**
|
||||
* A DuckDB query run with the lake attached as `dl` (`SELECT … FROM dl.<table>`). Name the
|
||||
* tables in the prompt, as a user would; column names are the model's to choose, so the
|
||||
* expectations look at values, not at columns.
|
||||
*/
|
||||
export interface PipelineRunQuery {
|
||||
name: string;
|
||||
sql: string;
|
||||
ducklake?: string;
|
||||
rowCount?: number;
|
||||
/** Every value appears in some cell of the result: numbers within 0.01, strings by prefix. */
|
||||
includesValues?: Array<string | number>;
|
||||
}
|
||||
|
||||
export interface PipelineRunResult {
|
||||
/** Why the run did not happen; nothing was asserted. */
|
||||
skipped?: string;
|
||||
error?: string;
|
||||
roots?: string[];
|
||||
nodes: Array<{
|
||||
path: string;
|
||||
deployError?: string;
|
||||
ran?: boolean;
|
||||
success?: boolean;
|
||||
/** `created_by` of the node's last run: `asset-<producer>` when a trigger ran it. */
|
||||
triggeredBy?: string;
|
||||
error?: string;
|
||||
}>;
|
||||
queries: Array<{ name: string; rows?: unknown[]; error?: string }>;
|
||||
}
|
||||
|
||||
export interface CliValidationSpec {
|
||||
@@ -363,6 +413,8 @@ export interface ModeRunContext {
|
||||
attempt: number;
|
||||
runs: number;
|
||||
verbose: boolean;
|
||||
/** `--execution-only`: the run validates nothing on the backend, `pipelineRun` included. */
|
||||
executionOnly?: boolean;
|
||||
onAssistantMessageStart?: () => void;
|
||||
onAssistantChunk?: (chunk: string) => void;
|
||||
onAssistantMessageEnd?: () => void;
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
validateAppState,
|
||||
validateCliWorkspace,
|
||||
validateGlobalState,
|
||||
validatePipelineRun,
|
||||
validateScriptState,
|
||||
validateAssistantExpectations,
|
||||
validateToolExpectations,
|
||||
@@ -622,6 +623,62 @@ describe("validateToolExpectations", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("validatePipelineRun", () => {
|
||||
const spec = {
|
||||
folder: "shop",
|
||||
queries: [
|
||||
{
|
||||
name: "daily",
|
||||
sql: "SELECT * FROM dl.orders_daily",
|
||||
rowCount: 2,
|
||||
includesValues: [2, 25, "2026-10-30"],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
it("fails a node no root reached, even when its table holds the right rows", () => {
|
||||
const checks = validatePipelineRun(spec, {
|
||||
nodes: [
|
||||
{ path: "f/shop/ingest", ran: true, success: true },
|
||||
{ path: "f/shop/daily", ran: false },
|
||||
],
|
||||
queries: [
|
||||
{
|
||||
name: "daily",
|
||||
rows: [
|
||||
{ day: "2026-10-30T00:00:00", n: 2, revenue: 25 },
|
||||
{ day: "2026-10-31T00:00:00", n: 3, revenue: 32.5 },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
const failed = checks.filter((c) => !c.passed).map((c) => c.name);
|
||||
expect(failed).toEqual(["pipeline node f/shop/daily runs and succeeds"]);
|
||||
});
|
||||
|
||||
it("fails a rollup started directly next to the ingest, even when it succeeded", () => {
|
||||
const checks = validatePipelineRun(
|
||||
{ ...spec, queries: [], maxRoots: 1 },
|
||||
{
|
||||
roots: ["f/shop/ingest", "f/shop/daily"],
|
||||
nodes: [
|
||||
{ path: "f/shop/ingest", ran: true, success: true },
|
||||
{ path: "f/shop/daily", ran: true, success: true },
|
||||
],
|
||||
queries: [],
|
||||
},
|
||||
);
|
||||
const failed = checks.filter((c) => !c.passed).map((c) => c.name);
|
||||
expect(failed).toEqual(["at most 1 pipeline node(s) start the pipeline"]);
|
||||
});
|
||||
|
||||
it("asserts nothing when the run was skipped", () => {
|
||||
expect(validatePipelineRun(spec, { skipped: "no storage", nodes: [], queries: [] })).toEqual(
|
||||
[],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("validateGlobalState", () => {
|
||||
it("accepts a required script draft", () => {
|
||||
const checks = validateGlobalState({
|
||||
|
||||
@@ -9,6 +9,8 @@ import type {
|
||||
FlowValidationSpec,
|
||||
GlobalValidationSpec,
|
||||
ModeRunOutput,
|
||||
PipelineRunResult,
|
||||
PipelineRunSpec,
|
||||
ToolValidationSpec,
|
||||
} from "./types";
|
||||
|
||||
@@ -55,6 +57,7 @@ export interface AppDatatableState {
|
||||
|
||||
export interface GlobalDraftState {
|
||||
drafts: GlobalDraft[];
|
||||
pipelineRun?: PipelineRunResult;
|
||||
}
|
||||
|
||||
export interface GlobalDraft {
|
||||
@@ -399,6 +402,84 @@ export function validateToolExpectations(input: {
|
||||
return checks;
|
||||
}
|
||||
|
||||
export function validatePipelineRun(
|
||||
spec: PipelineRunSpec,
|
||||
run: PipelineRunResult | undefined
|
||||
): BenchmarkCheck[] {
|
||||
// A run the backend could not host asserts nothing: the harness says why on the console.
|
||||
if (run?.skipped) {
|
||||
return [];
|
||||
}
|
||||
if (!run) {
|
||||
return [check("pipeline ran", false, "the harness recorded no pipeline run")];
|
||||
}
|
||||
const checks: BenchmarkCheck[] = [];
|
||||
checks.push(check("pipeline ran to completion", !run.error, run.error));
|
||||
if (spec.maxRoots !== undefined) {
|
||||
const roots = run.roots ?? [];
|
||||
checks.push(
|
||||
check(
|
||||
`at most ${spec.maxRoots} pipeline node(s) start the pipeline`,
|
||||
roots.length <= spec.maxRoots,
|
||||
`started directly, nothing upstream recorded as feeding them: ${roots.join(", ")}`
|
||||
)
|
||||
);
|
||||
}
|
||||
for (const node of run.nodes) {
|
||||
checks.push(
|
||||
check(
|
||||
`pipeline node ${node.path} deploys`,
|
||||
!node.deployError,
|
||||
node.deployError
|
||||
)
|
||||
);
|
||||
if (node.deployError) continue;
|
||||
checks.push(
|
||||
check(
|
||||
`pipeline node ${node.path} runs and succeeds`,
|
||||
node.ran === true && node.success === true,
|
||||
node.ran ? node.error : "never ran: no root reached it through an asset trigger"
|
||||
)
|
||||
);
|
||||
}
|
||||
for (const query of spec.queries ?? []) {
|
||||
const result = run.queries.find((q) => q.name === query.name);
|
||||
const rows = result?.rows;
|
||||
if (!rows) {
|
||||
checks.push(check(`pipeline data: ${query.name}`, false, result?.error ?? "not run"));
|
||||
continue;
|
||||
}
|
||||
const problems: string[] = [];
|
||||
if (query.rowCount !== undefined && rows.length !== query.rowCount) {
|
||||
problems.push(`expected ${query.rowCount} row(s), got ${rows.length}`);
|
||||
}
|
||||
const cells = rows.flatMap((row) =>
|
||||
row && typeof row === "object" ? Object.values(row) : [row]
|
||||
);
|
||||
for (const value of query.includesValues ?? []) {
|
||||
if (!cells.some((cell) => cellMatches(cell, value))) {
|
||||
problems.push(`no cell holds ${JSON.stringify(value)}`);
|
||||
}
|
||||
}
|
||||
checks.push(
|
||||
check(
|
||||
`pipeline data: ${query.name}`,
|
||||
problems.length === 0,
|
||||
problems.length ? `${problems.join("; ")} — rows: ${JSON.stringify(rows).slice(0, 400)}` : undefined
|
||||
)
|
||||
);
|
||||
}
|
||||
return checks;
|
||||
}
|
||||
|
||||
function cellMatches(cell: unknown, value: string | number): boolean {
|
||||
if (typeof value === "number") {
|
||||
const n = typeof cell === "number" ? cell : Number(cell);
|
||||
return cell !== null && cell !== "" && Number.isFinite(n) && Math.abs(n - value) < 0.01;
|
||||
}
|
||||
return typeof cell === "string" && cell.startsWith(value);
|
||||
}
|
||||
|
||||
export function validateGlobalState(input: {
|
||||
actual: GlobalDraftState;
|
||||
expected?: GlobalDraftState;
|
||||
@@ -466,6 +547,10 @@ export function validateGlobalState(input: {
|
||||
return checks;
|
||||
}
|
||||
|
||||
if (validate.pipelineRun) {
|
||||
checks.push(...validatePipelineRun(validate.pipelineRun, input.actual.pipelineRun));
|
||||
}
|
||||
|
||||
if (validate.draftCountAtLeast !== undefined) {
|
||||
checks.push(
|
||||
check(
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"user": {
|
||||
"username": "admin",
|
||||
"is_admin": true,
|
||||
"folders": ["shop"],
|
||||
"folders_read": ["shop"]
|
||||
},
|
||||
"workspace": {
|
||||
"ducklakes": ["main"],
|
||||
"objectStorage": {
|
||||
"files": [
|
||||
{
|
||||
"key": "raw/orders/2026-10-30.csv",
|
||||
"content": "order_id,customer,ordered_at,amount\n1001,acme,2026-10-30 09:12:00,10.00\n1002,globex,2026-10-30 17:40:00,15.00\n"
|
||||
},
|
||||
{
|
||||
"key": "raw/orders/2026-10-31.csv",
|
||||
"content": "order_id,customer,ordered_at,amount\n1003,acme,2026-10-31 08:01:00,5.00\n1004,initech,2026-10-31 11:30:00,7.50\n1005,globex,2026-10-31 23:59:00,20.00\n"
|
||||
},
|
||||
{
|
||||
"key": "raw/orders/2026-11-01.csv",
|
||||
"content": "order_id,customer,ordered_at,amount\n1006,umbrella,2026-11-01 14:00:00,40.00\n"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,9 @@ export function createGlobalModeRunner(
|
||||
): ModeRunner<GlobalInitialFixture, GlobalDraftState, GlobalDraftState> {
|
||||
return {
|
||||
mode: "global",
|
||||
concurrency: 3,
|
||||
// Each attempt holds a workspace of its own, and CE allows two besides `admins`; a third
|
||||
// attempt would wait for a slot, and the wait would count toward its duration.
|
||||
concurrency: 2,
|
||||
judgeThreshold: 80,
|
||||
async loadInitial(path) {
|
||||
return path ? await loadGlobalInitialFixture(path) : undefined;
|
||||
@@ -54,6 +56,9 @@ export function createGlobalModeRunner(
|
||||
sessionChat: context.evalCase?.runtime?.sessionChat,
|
||||
planMode: context.evalCase?.runtime?.planMode,
|
||||
profile: context.evalCase?.runtime?.profile,
|
||||
pipelineRun: context.executionOnly
|
||||
? undefined
|
||||
: (context.evalCase?.validate as GlobalValidationSpec | undefined)?.pipelineRun,
|
||||
maxIterations: context.evalCase?.runtime?.maxTurns,
|
||||
userAnswers: context.evalCase?.runtime?.userAnswers,
|
||||
provider: modelConfig.provider,
|
||||
|
||||
Generated
+98
-98
@@ -688,9 +688,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "async-executor"
|
||||
version = "1.14.0"
|
||||
version = "1.14.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
|
||||
checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37"
|
||||
dependencies = [
|
||||
"async-task",
|
||||
"concurrent-queue",
|
||||
@@ -709,7 +709,7 @@ dependencies = [
|
||||
"async-channel 2.5.0",
|
||||
"async-executor",
|
||||
"async-io 2.6.0",
|
||||
"async-lock 3.4.2",
|
||||
"async-lock 3.5.0",
|
||||
"blocking",
|
||||
"futures-lite 2.6.1",
|
||||
]
|
||||
@@ -774,9 +774,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "async-lock"
|
||||
version = "3.4.2"
|
||||
version = "3.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"
|
||||
checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f"
|
||||
dependencies = [
|
||||
"event-listener 5.4.2",
|
||||
"event-listener-strategy",
|
||||
@@ -2366,9 +2366,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.10.0"
|
||||
version = "1.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0"
|
||||
checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"jobserver",
|
||||
@@ -3055,9 +3055,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ctutils"
|
||||
version = "0.4.7"
|
||||
version = "0.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2376ffd6f96d8a9db59875b4b6b0237d6900b5baf64279714e05493ce64828a"
|
||||
checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
|
||||
dependencies = [
|
||||
"cmov",
|
||||
"subtle",
|
||||
@@ -7286,9 +7286,9 @@ checksum = "4754a1731458af0443709c9667302793d3f63cc90ec4ba4c8259f2b9515478e5"
|
||||
|
||||
[[package]]
|
||||
name = "jiff"
|
||||
version = "0.2.38"
|
||||
version = "0.2.39"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383"
|
||||
checksum = "3ac703058abac89e5c39b0b879dce2b6b14a4ba36600c7e7e3d0c60a6883ef3c"
|
||||
dependencies = [
|
||||
"defmt",
|
||||
"jiff-core",
|
||||
@@ -7303,9 +7303,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jiff-core"
|
||||
version = "0.1.1"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c"
|
||||
checksum = "aee43309eb53bafb8c36d35d6e444769c8f8e6206a9fbf7546f5db9d7d4a0e93"
|
||||
dependencies = [
|
||||
"defmt",
|
||||
"log",
|
||||
@@ -7313,9 +7313,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jiff-static"
|
||||
version = "0.2.38"
|
||||
version = "0.2.39"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c"
|
||||
checksum = "6dc32470c67eb7d0e9ccb74303fa925313dc04cecb1aa048beaa6f391e36a93d"
|
||||
dependencies = [
|
||||
"jiff-core",
|
||||
"proc-macro2",
|
||||
@@ -8325,7 +8325,7 @@ version = "0.12.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4293f18e7567a1caf3c584855554377025c65e0aa445344d04171f5ad63d19b9"
|
||||
dependencies = [
|
||||
"async-lock 3.4.2",
|
||||
"async-lock 3.5.0",
|
||||
"crossbeam-channel",
|
||||
"crossbeam-epoch",
|
||||
"crossbeam-utils",
|
||||
@@ -11259,7 +11259,7 @@ version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8bf7840285c321c3ab20e752a9afb95548c75cd7f4632a0627cea3507e310c1"
|
||||
dependencies = [
|
||||
"async-lock 3.4.2",
|
||||
"async-lock 3.5.0",
|
||||
"hashbrown 0.16.1",
|
||||
"relative-path",
|
||||
"rquickjs-sys",
|
||||
@@ -15259,9 +15259,9 @@ checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64"
|
||||
|
||||
[[package]]
|
||||
name = "vsock"
|
||||
version = "0.5.4"
|
||||
version = "0.5.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ba782755fc073877e567c2253c0be48e4aa9a254c232d36d3985dfae0bd5205"
|
||||
checksum = "9b7d4dba01e366e2ffbdf0700b1876f747c548db72dced534de41c54945c0148"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"nix 0.31.3",
|
||||
@@ -15624,7 +15624,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-nats",
|
||||
@@ -15714,7 +15714,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-ai"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"async-stream",
|
||||
"async-trait",
|
||||
@@ -15749,7 +15749,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-alerting"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"chrono",
|
||||
@@ -15762,7 +15762,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"argon2",
|
||||
@@ -15905,7 +15905,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-agent-workers"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"chrono",
|
||||
@@ -15929,7 +15929,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-assets"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"chrono",
|
||||
@@ -15946,7 +15946,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-auth"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
@@ -15972,7 +15972,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-client"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"reqwest 0.12.28",
|
||||
"serde",
|
||||
@@ -15982,7 +15982,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-configs"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"chrono",
|
||||
@@ -15999,7 +15999,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-debug"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"base64 0.22.1",
|
||||
@@ -16021,7 +16021,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-embeddings"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
@@ -16044,7 +16044,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-flow-conversations"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"chrono",
|
||||
@@ -16060,7 +16060,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-flows"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"chrono",
|
||||
@@ -16082,7 +16082,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-groups"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"chrono",
|
||||
@@ -16104,7 +16104,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-inputs"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"chrono",
|
||||
@@ -16118,7 +16118,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-integration-tests"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-nats",
|
||||
@@ -16154,7 +16154,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-jobs"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
@@ -16180,7 +16180,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-npm-proxy"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"chrono",
|
||||
@@ -16208,7 +16208,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-openapi"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
@@ -16230,7 +16230,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-schedule"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"chrono",
|
||||
@@ -16250,7 +16250,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-scripts"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
@@ -16292,7 +16292,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-settings"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
@@ -16322,7 +16322,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-sse"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"lazy_static",
|
||||
"serde",
|
||||
@@ -16334,7 +16334,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-users"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"axum",
|
||||
@@ -16358,7 +16358,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-workers"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"chrono",
|
||||
@@ -16373,7 +16373,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-api-workspaces"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"chrono",
|
||||
@@ -16412,7 +16412,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-audit"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"lazy_static",
|
||||
@@ -16427,7 +16427,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-autoscaling"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
@@ -16446,7 +16446,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-common"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"aho-corasick",
|
||||
@@ -16564,7 +16564,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-dep-map"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"futures",
|
||||
@@ -16584,7 +16584,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-git-sync"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"regex",
|
||||
"serde",
|
||||
@@ -16601,7 +16601,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-indexer"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"astral-tokio-tar",
|
||||
@@ -16628,7 +16628,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-jseval"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"futures",
|
||||
@@ -16645,7 +16645,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-macros"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"itertools 0.14.0",
|
||||
"lazy_static",
|
||||
@@ -16661,7 +16661,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-mcp"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
@@ -16683,7 +16683,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-native-triggers"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
@@ -16714,7 +16714,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-oauth"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"arc-swap",
|
||||
@@ -16739,7 +16739,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-object-store"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-stream",
|
||||
@@ -16775,7 +16775,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-operator"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"futures",
|
||||
@@ -16794,7 +16794,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"convert_case 0.6.0",
|
||||
"serde",
|
||||
@@ -16803,7 +16803,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-bash"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -16815,7 +16815,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-csharp"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"serde_json",
|
||||
@@ -16827,7 +16827,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-go"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"gosyn",
|
||||
@@ -16839,7 +16839,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-graphql"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -16851,7 +16851,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-java"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"serde_json",
|
||||
@@ -16863,7 +16863,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-nu"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"nu-parser",
|
||||
@@ -16874,7 +16874,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-php"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"itertools 0.14.0",
|
||||
@@ -16885,7 +16885,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-py"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"itertools 0.14.0",
|
||||
@@ -16897,7 +16897,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-py-asset"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ruff_python_ast",
|
||||
@@ -16908,7 +16908,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-py-imports"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-recursion",
|
||||
@@ -16931,7 +16931,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-r"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"serde_json",
|
||||
@@ -16943,7 +16943,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-ruby"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -16957,7 +16957,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-rust"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"convert_case 0.6.0",
|
||||
@@ -16974,7 +16974,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-sql"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -16987,7 +16987,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-sql-asset"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"serde",
|
||||
@@ -16999,7 +16999,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-ts"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -17017,7 +17017,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-ts-asset"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"serde-wasm-bindgen",
|
||||
@@ -17033,7 +17033,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-wac"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ruff_python_ast",
|
||||
@@ -17050,7 +17050,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-yaml"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -17064,7 +17064,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-queue"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-recursion",
|
||||
@@ -17103,7 +17103,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-runtime-nativets"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"const_format",
|
||||
@@ -17141,7 +17141,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-sql-datatype-parser-wasm"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"wasm-bindgen",
|
||||
@@ -17152,7 +17152,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-store"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-recursion",
|
||||
@@ -17187,7 +17187,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-test-utils"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
@@ -17211,7 +17211,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-trigger"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
@@ -17244,7 +17244,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-trigger-amqp"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
@@ -17271,7 +17271,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-trigger-azure"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
@@ -17304,7 +17304,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-trigger-email"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
@@ -17324,7 +17324,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-trigger-gcp"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
@@ -17358,7 +17358,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-trigger-http"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
@@ -17395,7 +17395,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-trigger-kafka"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
@@ -17418,7 +17418,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-trigger-mqtt"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
@@ -17442,7 +17442,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-trigger-nats"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-nats",
|
||||
@@ -17466,7 +17466,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-trigger-postgres"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
@@ -17501,7 +17501,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-trigger-sqs"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
@@ -17529,7 +17529,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-trigger-websocket"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
@@ -17555,7 +17555,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-types"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bitflags 2.13.2",
|
||||
@@ -17574,7 +17574,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-worker"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-once-cell",
|
||||
@@ -17692,7 +17692,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-worker-volumes"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures",
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "windmill"
|
||||
version = "1.856.0"
|
||||
version = "1.858.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.856.0"
|
||||
version = "1.858.0"
|
||||
authors = ["Ruben Fiszel <ruben@windmill.dev>"]
|
||||
edition = "2021"
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
bd75bb821b30723c2789081cac004ee134bd10a1
|
||||
da6bb1965702eb57237882e5fda6179f72294a06
|
||||
|
||||
@@ -43,9 +43,11 @@ pub fn parse_assets(input: &str) -> anyhow::Result<ParseAssetsOutput> {
|
||||
// target, keep inference only when every tagged entry shares one output
|
||||
// asset — otherwise it's ambiguous which asset the flat list describes, so
|
||||
// drop it rather than show false dependencies.
|
||||
// A target naming no table is named after the script, which this parser does not know.
|
||||
let target = pipeline
|
||||
.materialize
|
||||
.as_ref()
|
||||
.filter(|m| !m.names_no_table())
|
||||
.map(|m| (m.target_kind, m.target_path.clone()));
|
||||
let inferred: Vec<ColumnLineage> = match &target {
|
||||
Some(t) => collector
|
||||
|
||||
+24
-24
@@ -6340,7 +6340,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
||||
|
||||
[[package]]
|
||||
name = "windmill-common"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"aho-corasick",
|
||||
@@ -6430,7 +6430,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-macros"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -6442,7 +6442,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"convert_case",
|
||||
"serde",
|
||||
@@ -6451,7 +6451,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-bash"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -6463,7 +6463,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-csharp"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"serde_json",
|
||||
@@ -6475,7 +6475,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-go"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"gosyn",
|
||||
@@ -6487,7 +6487,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-graphql"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -6499,7 +6499,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-java"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"serde_json",
|
||||
@@ -6511,7 +6511,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-nu"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"nu-parser",
|
||||
@@ -6522,7 +6522,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-php"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"itertools 0.14.0",
|
||||
@@ -6533,7 +6533,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-py"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"itertools 0.14.0",
|
||||
@@ -6545,7 +6545,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-py-asset"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ruff_python_ast",
|
||||
@@ -6556,7 +6556,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-py-imports"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-recursion",
|
||||
@@ -6579,7 +6579,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-r"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"serde_json",
|
||||
@@ -6591,7 +6591,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-ruby"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -6605,7 +6605,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-rust"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"convert_case",
|
||||
@@ -6622,7 +6622,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-sql"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -6635,7 +6635,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-sql-asset"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"serde",
|
||||
@@ -6647,7 +6647,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-ts"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -6665,7 +6665,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-ts-asset"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"serde-wasm-bindgen",
|
||||
@@ -6681,7 +6681,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-wac"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"ruff_python_ast",
|
||||
@@ -6698,7 +6698,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-wasm"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"getrandom 0.2.17",
|
||||
@@ -6730,7 +6730,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-parser-yaml"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"lazy_static",
|
||||
@@ -6744,7 +6744,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "windmill-types"
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bitflags",
|
||||
|
||||
@@ -12,7 +12,7 @@ resolver = "2"
|
||||
members = ["."]
|
||||
|
||||
[workspace.package]
|
||||
version = "1.856.0"
|
||||
version = "1.858.0"
|
||||
edition = "2021"
|
||||
authors = ["Ruben Fiszel <ruben@windmill.dev>"]
|
||||
|
||||
|
||||
@@ -367,6 +367,60 @@ impl MaterializeSpec {
|
||||
targets.extend(self.scd2_current_target());
|
||||
targets
|
||||
}
|
||||
|
||||
/// A DuckLake target naming no table (`// materialize`, `// materialize ducklake`,
|
||||
/// `// materialize ducklake://<lake>`) writes `<lake>/<script name>`, as a dbt model is
|
||||
/// named after its file. Every surface that reads the target resolves it through here,
|
||||
/// with the script's path, so deploy, the runtime and the graphs agree on the table.
|
||||
/// A DuckLake target that is a lake alone: `<lake>/<table>` and `<lake>.<table>` name one.
|
||||
pub fn names_no_table(&self) -> bool {
|
||||
self.target_kind == AssetKind::Ducklake
|
||||
&& !self.target_path.contains('/')
|
||||
&& !self.target_path.contains('.')
|
||||
}
|
||||
|
||||
pub fn resolve_table(&mut self, script_path: &str) {
|
||||
if self.names_no_table() {
|
||||
if let Some(table) = default_table_name(script_path) {
|
||||
self.target_path = format!("{}/{}", self.target_path, table);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The table a script materializes when its annotation names none: its path's last segment,
|
||||
/// with every character DuckDB would need quoted replaced by `_`, and a leading `_` before a
|
||||
/// leading digit, since the generated SQL names the table unquoted.
|
||||
pub fn default_table_name(script_path: &str) -> Option<String> {
|
||||
let name = script_path.rsplit('/').next().unwrap_or("").trim();
|
||||
(!name.is_empty()).then(|| {
|
||||
let table: String = name
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c.is_ascii_alphanumeric() || c == '_' {
|
||||
c
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if table.starts_with(|c: char| c.is_ascii_digit()) {
|
||||
format!("_{table}")
|
||||
} else {
|
||||
table
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
impl PipelineAnnotations {
|
||||
/// The annotations of the script at `script_path`, with a materialize target that names
|
||||
/// no table resolved (`MaterializeSpec::resolve_table`).
|
||||
pub fn for_script(mut self, script_path: &str) -> Self {
|
||||
if let Some(m) = self.materialize.as_mut() {
|
||||
m.resolve_table(script_path);
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
// dbt's `on_schema_change`, covering both the save-time contract check and the
|
||||
@@ -1359,8 +1413,20 @@ fn parse_materialize_spec(s: &str) -> Option<MaterializeSpec> {
|
||||
(false, false, s)
|
||||
};
|
||||
let mut it = rest.trim().splitn(2, char::is_whitespace);
|
||||
let asset_tok = it.next()?;
|
||||
let opts_str = it.next().unwrap_or("");
|
||||
let first = it.next().unwrap_or("");
|
||||
// No target, or options alone, is the default lake: `resolve_table` names the table
|
||||
// after the script once its path is known.
|
||||
let names_target = first.contains("://")
|
||||
|| (!first.is_empty() && first != "append" && first != "history" && !first.contains('='));
|
||||
// `manual` writes its own DDL, so it has to say what it writes.
|
||||
if manual && !names_target {
|
||||
return None;
|
||||
}
|
||||
let (asset_tok, opts_str) = if names_target {
|
||||
(first, it.next().unwrap_or(""))
|
||||
} else {
|
||||
("ducklake", rest.trim())
|
||||
};
|
||||
let (target_kind, path) = parse_asset_syntax(asset_tok.trim(), true)?;
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
@@ -1814,8 +1880,17 @@ mod pipeline_annotation_tests {
|
||||
fn a_whole_relation_is_three_non_empty_segments() {
|
||||
assert!(is_full_relation_path("main/analytics/orders"));
|
||||
assert!(is_full_relation_path("main/archive.sales/orders"));
|
||||
for partial in ["main", "main/analytics", "main/analytics/orders/x", "", "main//orders"] {
|
||||
assert!(!is_full_relation_path(partial), "{partial} is not a relation");
|
||||
for partial in [
|
||||
"main",
|
||||
"main/analytics",
|
||||
"main/analytics/orders/x",
|
||||
"",
|
||||
"main//orders",
|
||||
] {
|
||||
assert!(
|
||||
!is_full_relation_path(partial),
|
||||
"{partial} is not a relation"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2681,6 +2756,45 @@ mod pipeline_annotation_tests {
|
||||
assert!(!m.manual);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialize_without_table_is_named_after_the_script() {
|
||||
for code in [
|
||||
"-- materialize",
|
||||
"-- materialize ducklake",
|
||||
"-- materialize ducklake://main",
|
||||
"-- materialize append",
|
||||
] {
|
||||
let m = parse_pipeline_annotations(code)
|
||||
.for_script("f/shop/orders-daily")
|
||||
.materialize
|
||||
.expect(code);
|
||||
assert_eq!(m.target_path, "main/orders_daily", "{code}");
|
||||
}
|
||||
let m = parse_pipeline_annotations("-- materialize ducklake://lake/orders")
|
||||
.for_script("f/shop/orders_daily")
|
||||
.materialize
|
||||
.unwrap();
|
||||
assert_eq!(m.target_path, "lake/orders");
|
||||
// A URI is a target even when it holds `=`.
|
||||
let m = parse_pipeline_annotations("-- materialize ducklake://main/orders=2026")
|
||||
.for_script("f/shop/ingest")
|
||||
.materialize
|
||||
.unwrap();
|
||||
assert_eq!(m.target_path, "main/orders=2026");
|
||||
// The generated SQL names the table unquoted, so it cannot start with a digit.
|
||||
let m = parse_pipeline_annotations("-- materialize")
|
||||
.for_script("f/shop/2026_orders")
|
||||
.materialize
|
||||
.unwrap();
|
||||
assert_eq!(m.target_path, "main/_2026_orders");
|
||||
// One `_` per character, as the TS and CLI mirrors count them, whatever its width.
|
||||
let m = parse_pipeline_annotations("-- materialize")
|
||||
.for_script("f/shop/orders_𐐀")
|
||||
.materialize
|
||||
.unwrap();
|
||||
assert_eq!(m.target_path, "main/orders__");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialize_manual_only_is_dropped() {
|
||||
// `manual` with no target is not a valid materialization.
|
||||
|
||||
@@ -859,6 +859,41 @@
|
||||
"mute_all": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "materialize without a target is the default lake, its table named later",
|
||||
"code": "-- pipeline\n-- materialize\nSELECT 1;",
|
||||
"expected": {
|
||||
"in_pipeline": true,
|
||||
"asset_triggers": [],
|
||||
"native_triggers": [],
|
||||
"partition": null,
|
||||
"freshness": null,
|
||||
"tag": null,
|
||||
"retry": null,
|
||||
"materialize": {
|
||||
"target_kind": "ducklake",
|
||||
"target_path": "main"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "materialize with options only is the default lake",
|
||||
"code": "-- pipeline\n-- materialize key=order_id\nSELECT 1;",
|
||||
"expected": {
|
||||
"in_pipeline": true,
|
||||
"asset_triggers": [],
|
||||
"native_triggers": [],
|
||||
"partition": null,
|
||||
"freshness": null,
|
||||
"tag": null,
|
||||
"retry": null,
|
||||
"materialize": {
|
||||
"target_kind": "ducklake",
|
||||
"target_path": "main",
|
||||
"unique_key": "order_id"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "on asset ref strips trailing key=value opts",
|
||||
"code": "// pipeline\n// on ducklake://main.orders debounce=60s\nselect 1",
|
||||
|
||||
@@ -22,16 +22,17 @@
|
||||
//! sent as a POST, gets through.
|
||||
//!
|
||||
//! No runnable exists and no Hub is contacted. A request that gets past the guard fails as
|
||||
//! not-found on a workspace path, and on the non-numeric version in `hub/x/...` for a Hub
|
||||
//! path, which is rejected while resolving the runnable, before any call to the Hub.
|
||||
//! not-found on a workspace path, and for a Hub path on fetching it from a Hub pointed at a
|
||||
//! closed port. Its id is above `PRIVATE_HUB_MIN_VERSION`, so the fetch does not fall back to
|
||||
//! the public Hub.
|
||||
|
||||
use reqwest::StatusCode;
|
||||
use sqlx::{Pool, Postgres};
|
||||
use windmill_test_utils::*;
|
||||
|
||||
const HUB_GETS: [&str; 2] = [
|
||||
"run_wait_result/p/hub/x/absent",
|
||||
"run_and_stream/p/hub/x/absent",
|
||||
"run_wait_result/p/hub/10000001/absent",
|
||||
"run_and_stream/p/hub/10000001/absent",
|
||||
];
|
||||
const WORKSPACE_GETS: [&str; 2] = [
|
||||
"run_wait_result/p/u/test-user/absent",
|
||||
@@ -49,6 +50,7 @@ async fn test_cross_site_get_cannot_run_hub_scripts(db: Pool<Postgres>) -> anyho
|
||||
initialize_tracing().await;
|
||||
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
windmill_common::HUB_BASE_URL.store(std::sync::Arc::new("http://127.0.0.1:1".to_string()));
|
||||
let base = format!(
|
||||
"http://localhost:{}/api/w/test-workspace/jobs",
|
||||
server.addr.port()
|
||||
@@ -91,6 +93,16 @@ async fn test_cross_site_get_cannot_run_hub_scripts(db: Pool<Postgres>) -> anyho
|
||||
}
|
||||
}
|
||||
|
||||
// Two leading `/` are refused before the guard. Stripped one at a time, the guard would read
|
||||
// `/hub/…` as a workspace path and the queue, stripping the next, would run the Hub script.
|
||||
let path = "run_and_stream/p///hub/10000001/absent?skip_preprocessor=true";
|
||||
let (status, body) = send(cookie_get(path).header("Sec-Fetch-Site", "cross-site")).await?;
|
||||
assert_eq!(
|
||||
status,
|
||||
StatusCode::BAD_REQUEST,
|
||||
"{path} must be refused: {body}"
|
||||
);
|
||||
|
||||
// ---- Scope: the same request to a workspace script is not refused.
|
||||
for path in WORKSPACE_GETS {
|
||||
let (status, body) = send(cookie_get(path).header("Sec-Fetch-Site", "cross-site")).await?;
|
||||
@@ -129,8 +141,8 @@ async fn test_cross_site_get_cannot_run_hub_scripts(db: Pool<Postgres>) -> anyho
|
||||
for (name, req) in allowed {
|
||||
let (status, body) = send(req).await?;
|
||||
assert!(
|
||||
body.contains("Invalid hub script version"),
|
||||
"{name} must get past the guard to runnable resolution (got {status}): {body}"
|
||||
body.contains("127.0.0.1:1"),
|
||||
"{name} must get past the guard to the Hub fetch (got {status}): {body}"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
//! `jobs/recent_runs`: it aggregates over the workspace through `user_db`, which applies RLS but
|
||||
//! not a token's `if_jobs:filter_tags` scope, so the handler filters on it itself; and it reports a
|
||||
//! resolved failure apart from an unresolved one.
|
||||
|
||||
use sqlx::{Pool, Postgres};
|
||||
use windmill_test_utils::*;
|
||||
|
||||
// From the `jobs_read_auth` fixture, both runs of test-user-2: one tagged `deno`, one `flow`.
|
||||
const DENO_JOB: &str = "14141414-1414-1414-1414-141414141414";
|
||||
const FLOW_JOB: &str = "15151515-1515-1515-1515-151515151515";
|
||||
|
||||
async fn recent_runs(port: u16, token: &str) -> String {
|
||||
recent_runs_query(port, token, "").await
|
||||
}
|
||||
|
||||
async fn recent_runs_query(port: u16, token: &str, query: &str) -> String {
|
||||
let resp = reqwest::Client::new()
|
||||
.get(format!(
|
||||
"http://localhost:{port}/api/w/test-workspace/jobs/recent_runs{query}"
|
||||
))
|
||||
.header("Authorization", format!("Bearer {token}"))
|
||||
.send()
|
||||
.await
|
||||
.expect("request");
|
||||
assert!(resp.status().is_success(), "{}", resp.status());
|
||||
resp.text().await.expect("body")
|
||||
}
|
||||
|
||||
#[sqlx::test(fixtures("base", "jobs_read_auth"))]
|
||||
async fn test_recent_runs_honors_tag_scope(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
let port = server.addr.port();
|
||||
|
||||
let unscoped = recent_runs(port, "SECRET_TOKEN_2").await;
|
||||
assert!(unscoped.contains(DENO_JOB), "{unscoped}");
|
||||
assert!(unscoped.contains(FLOW_JOB), "{unscoped}");
|
||||
|
||||
// SCOPED_DENO_TOKEN is test-user-2 restricted to `if_jobs:filter_tags:deno`.
|
||||
let scoped = recent_runs(port, "SCOPED_DENO_TOKEN").await;
|
||||
assert!(scoped.contains(DENO_JOB), "{scoped}");
|
||||
assert!(!scoped.contains(FLOW_JOB), "{scoped}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn insert_root_run(
|
||||
db: &Pool<Postgres>,
|
||||
id: &str,
|
||||
status: &str,
|
||||
resolved: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO v2_job (id, workspace_id, created_by, permissioned_as, permissioned_as_email,
|
||||
kind, script_lang, runnable_path, tag, visible_to_owner)
|
||||
VALUES ($1::uuid, 'test-workspace', 'test-user-2', 'u/test-user-2', 'test2@windmill.dev',
|
||||
'script', 'deno', 'u/test-user-2/flaky', 'deno', true)",
|
||||
)
|
||||
.bind(id)
|
||||
.execute(db)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO v2_job_completed (id, workspace_id, duration_ms, status)
|
||||
VALUES ($1::uuid, 'test-workspace', 10, $2::job_status)",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(status)
|
||||
.execute(db)
|
||||
.await?;
|
||||
if resolved {
|
||||
sqlx::query(
|
||||
"INSERT INTO job_resolution (job_id, workspace_id) VALUES ($1::uuid, 'test-workspace')",
|
||||
)
|
||||
.bind(id)
|
||||
.execute(db)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A resolved failure is `resolved`, not `failure`: Home's failed counts leave it out, and the
|
||||
/// failed ids asked for one item are the failures that item counts.
|
||||
#[sqlx::test(fixtures("base", "jobs_read_auth"))]
|
||||
async fn test_recent_runs_resolved_failures(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
insert_root_run(&db, "a0000000-0000-0000-0000-000000000001", "failure", true).await?;
|
||||
insert_root_run(&db, "a0000000-0000-0000-0000-000000000002", "failure", false).await?;
|
||||
insert_root_run(&db, "a0000000-0000-0000-0000-000000000003", "canceled", true).await?;
|
||||
// A failed single-step flow wrapping a flow at the same path: the flow's failure, not the
|
||||
// script's, though a job listing by path and kind cannot tell them apart.
|
||||
sqlx::query(
|
||||
"INSERT INTO v2_job (id, workspace_id, created_by, permissioned_as, permissioned_as_email,
|
||||
kind, script_lang, runnable_path, tag, visible_to_owner, raw_flow)
|
||||
VALUES ('a0000000-0000-0000-0000-000000000004', 'test-workspace', 'test-user-2',
|
||||
'u/test-user-2', 'test2@windmill.dev', 'singlestepflow', 'deno', 'u/test-user-2/flaky',
|
||||
'deno', true,
|
||||
'{\"modules\": [{\"id\": \"a\", \"value\": {\"type\": \"flow\", \"path\": \"u/test-user-2/flaky\"}}]}')",
|
||||
)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO v2_job_completed (id, workspace_id, duration_ms, status)
|
||||
VALUES ('a0000000-0000-0000-0000-000000000004', 'test-workspace', 10, 'failure')",
|
||||
)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
|
||||
let body: serde_json::Value = serde_json::from_str(
|
||||
&recent_runs_query(
|
||||
server.addr.port(),
|
||||
"SECRET_TOKEN_2",
|
||||
"?failed_ids_kind=script&failed_ids_path=u/test-user-2/flaky",
|
||||
)
|
||||
.await,
|
||||
)?;
|
||||
let item = body["items"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|i| i["path"] == "u/test-user-2/flaky" && i["kind"] == "script")
|
||||
.expect("item");
|
||||
let status_of = |id: &str| {
|
||||
item["runs"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|r| r["id"] == id)
|
||||
.map(|r| r["status"].clone())
|
||||
};
|
||||
assert_eq!(status_of("a0000000-0000-0000-0000-000000000001"), Some("resolved".into()));
|
||||
assert_eq!(status_of("a0000000-0000-0000-0000-000000000002"), Some("failure".into()));
|
||||
assert_eq!(status_of("a0000000-0000-0000-0000-000000000003"), Some("canceled".into()));
|
||||
assert_eq!(item["failed_runs"], 1, "{body}");
|
||||
// Only the item named in the query carries its ids, and they are its own unresolved failures.
|
||||
assert_eq!(
|
||||
item["failed_run_ids"],
|
||||
serde_json::json!(["a0000000-0000-0000-0000-000000000002"]),
|
||||
"{body}"
|
||||
);
|
||||
let flow = body["items"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|i| i["path"] == "u/test-user-2/flaky" && i["kind"] == "flow")
|
||||
.expect("flow item");
|
||||
assert!(flow.get("failed_run_ids").is_none(), "{body}");
|
||||
assert_eq!(body["failed_runs"], 2, "{body}");
|
||||
Ok(())
|
||||
}
|
||||
@@ -1980,7 +1980,7 @@ pub async fn asset_graph_for(
|
||||
.map(|r| {
|
||||
(
|
||||
r.path.clone(),
|
||||
windmill_common::assets::parse_pipeline_annotations(&r.content),
|
||||
windmill_common::assets::parse_pipeline_annotations(&r.content).for_script(&r.path),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -54,6 +54,7 @@ use windmill_common::{
|
||||
jwt::JWT_SECRET,
|
||||
scripts::ScriptLang,
|
||||
users::username_to_permissioned_as,
|
||||
workspaces::check_role_can_code,
|
||||
DB,
|
||||
};
|
||||
|
||||
@@ -138,6 +139,7 @@ pub fn workspaced_service() -> Router {
|
||||
.route("/sign", post(sign_debug_request))
|
||||
.route("/sign_expression", post(sign_expression))
|
||||
.route("/sign_multiplayer", post(sign_multiplayer))
|
||||
.route("/sign_lsp", post(sign_lsp))
|
||||
}
|
||||
|
||||
/// JWKS response containing the public key for debug token verification
|
||||
@@ -698,7 +700,7 @@ async fn sign_expression(
|
||||
Ok(Json(SignedExpressionPayload { token }))
|
||||
}
|
||||
|
||||
/// JWT claims for multiplayer session tokens
|
||||
/// JWT claims for multiplayer and language server session tokens
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct MultiplayerTokenClaims {
|
||||
/// Workspace ID
|
||||
@@ -709,7 +711,7 @@ pub struct MultiplayerTokenClaims {
|
||||
pub iat: i64,
|
||||
/// Expiration (Unix timestamp)
|
||||
pub exp: i64,
|
||||
/// Token purpose (always "multiplayer")
|
||||
/// Token purpose ("multiplayer" or "lsp")
|
||||
pub purpose: String,
|
||||
}
|
||||
|
||||
@@ -724,6 +726,28 @@ pub struct SignedMultiplayerPayload {
|
||||
async fn sign_multiplayer(
|
||||
authed: ApiAuthed,
|
||||
Path(w_id): Path<String>,
|
||||
) -> JsonResult<SignedMultiplayerPayload> {
|
||||
sign_session_token(w_id, authed.email, "multiplayer").await
|
||||
}
|
||||
|
||||
/// Sign a language server session request, verified by the windmill_extra gateway against
|
||||
/// /api/debug/jwks before it forwards the connection to the language servers.
|
||||
///
|
||||
/// Gated on the role's `code` capability, not `is_operator`: the language servers only analyse
|
||||
/// backend script languages, and a restricted role may still hold `code`.
|
||||
async fn sign_lsp(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
) -> JsonResult<SignedMultiplayerPayload> {
|
||||
check_role_can_code(&db, &w_id, &authed, "use the editor language servers").await?;
|
||||
sign_session_token(w_id, authed.email, "lsp").await
|
||||
}
|
||||
|
||||
async fn sign_session_token(
|
||||
w_id: String,
|
||||
email: String,
|
||||
purpose: &str,
|
||||
) -> JsonResult<SignedMultiplayerPayload> {
|
||||
let key_guard = DEBUG_SIGNING_KEY.read().await;
|
||||
let signing_key = key_guard.as_ref().ok_or_else(|| {
|
||||
@@ -735,10 +759,10 @@ async fn sign_multiplayer(
|
||||
|
||||
let claims = MultiplayerTokenClaims {
|
||||
workspace_id: w_id,
|
||||
email: authed.email,
|
||||
email,
|
||||
iat: now_ts,
|
||||
exp,
|
||||
purpose: "multiplayer".to_string(),
|
||||
purpose: purpose.to_string(),
|
||||
};
|
||||
|
||||
let header = serde_json::json!({
|
||||
|
||||
@@ -1988,7 +1988,7 @@ async fn create_script_internal<'c>(
|
||||
// bare `// pipeline` marker is the opt-in signal for pipeline
|
||||
// membership; parsed writes tell us what is produced (we don't record
|
||||
// them in auto_kind itself).
|
||||
let pipeline_annotations = parse_pipeline_annotations(&ns.content);
|
||||
let pipeline_annotations = parse_pipeline_annotations(&ns.content).for_script(&ns.path);
|
||||
// `// materialize` names what this script produces. Two target kinds, and the
|
||||
// runtime behind each is what constrains the annotation:
|
||||
// • `ducklake://<name>/<table>` — the DuckDB executor generates the write
|
||||
@@ -5139,6 +5139,8 @@ async fn get_ci_test_results_batch(
|
||||
struct CheckSchemaContractsRequest {
|
||||
language: ScriptLang,
|
||||
content: String,
|
||||
#[serde(default)]
|
||||
path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -5163,7 +5165,10 @@ async fn check_schema_contracts(
|
||||
) -> JsonResult<CheckSchemaContractsResponse> {
|
||||
let assets = crate::asset_inference::effective_script_assets(&req.language, &req.content, None)
|
||||
.unwrap_or_default();
|
||||
let ann = parse_pipeline_annotations(&req.content);
|
||||
let mut ann = parse_pipeline_annotations(&req.content);
|
||||
if let Some(path) = req.path.as_deref() {
|
||||
ann = ann.for_script(path);
|
||||
}
|
||||
let mut tx = user_db.begin(&authed).await?;
|
||||
let warnings = windmill_common::schema_contracts::check_schema_contracts(
|
||||
&mut tx,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: "3.0.3"
|
||||
|
||||
info:
|
||||
version: 1.856.0
|
||||
version: 1.858.0
|
||||
title: Windmill API
|
||||
|
||||
contact:
|
||||
@@ -12240,6 +12240,11 @@ paths:
|
||||
$ref: "#/components/schemas/ScriptLang"
|
||||
content:
|
||||
type: string
|
||||
path:
|
||||
type: string
|
||||
description: |
|
||||
The script's path. A `// materialize` that names no table writes the
|
||||
table named after the script, so without it such a target is not checked.
|
||||
responses:
|
||||
"200":
|
||||
description: contract warnings (empty when all references match)
|
||||
@@ -14806,6 +14811,84 @@ paths:
|
||||
type: boolean
|
||||
description: more buckets matched than were returned, so summing them under-reports
|
||||
|
||||
/w/{workspace}/ai_session_tools/{name}:
|
||||
post:
|
||||
summary: run one of the AI session's tools as the calling user
|
||||
description: The in-app chat's entry to the session toolset the MCP server also serves. Refused for job tokens and scoped tokens.
|
||||
operationId: callAiSessionTool
|
||||
tags:
|
||||
- ai
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/WorkspaceId"
|
||||
- name: name
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
args:
|
||||
description: the tool's arguments, as the model sent them
|
||||
context:
|
||||
type: object
|
||||
description: browser-held state the tool reads
|
||||
additionalProperties: true
|
||||
properties:
|
||||
live_editors:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
required:
|
||||
- kind
|
||||
- storage_path
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
storage_path:
|
||||
type: string
|
||||
effective_path:
|
||||
type: string
|
||||
cells:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
required:
|
||||
- kind
|
||||
- storage_path
|
||||
- value
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
storage_path:
|
||||
type: string
|
||||
value: {}
|
||||
responses:
|
||||
"200":
|
||||
description: what the model reads, and what the chat applies
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
- text
|
||||
- is_error
|
||||
- effects
|
||||
properties:
|
||||
text:
|
||||
type: string
|
||||
is_error:
|
||||
type: boolean
|
||||
effects:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
additionalProperties: true
|
||||
|
||||
/w/{workspace}/ai/sessions/list:
|
||||
get:
|
||||
summary: list the calling user's AI session backups in the workspace object storage
|
||||
@@ -17953,6 +18036,101 @@ paths:
|
||||
type: string
|
||||
description: Summary of deleted jobs and rows
|
||||
|
||||
/w/{workspace}/jobs/recent_runs:
|
||||
get:
|
||||
summary: list what ran recently, one entry per script, flow or agent
|
||||
operationId: listRecentRuns
|
||||
tags:
|
||||
- job
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/WorkspaceId"
|
||||
- name: folder
|
||||
description: only runs of items in this folder
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
- name: failed_ids_kind
|
||||
description: with failed_ids_path, the item whose unresolved failed run ids to list in failed_run_ids
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
enum: [script, flow, agent]
|
||||
- name: failed_ids_path
|
||||
description: with failed_ids_kind, the path of that item
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
description: runs that completed in the window or are running, grouped by item, newest run first
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
window_hours:
|
||||
type: integer
|
||||
capped:
|
||||
description: the window holds more runs than were read, so counts cover the newest ones only
|
||||
type: boolean
|
||||
total_runs:
|
||||
type: integer
|
||||
failed_runs:
|
||||
type: integer
|
||||
failing_items:
|
||||
type: integer
|
||||
running_items:
|
||||
type: integer
|
||||
items:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
path:
|
||||
type: string
|
||||
kind:
|
||||
type: string
|
||||
enum: [script, flow, agent]
|
||||
summary:
|
||||
type: string
|
||||
status:
|
||||
$ref: "#/components/schemas/RecentRunStatus"
|
||||
failed_runs:
|
||||
description: unresolved failed runs of the item over the whole window, not only those in runs
|
||||
type: integer
|
||||
failed_run_ids:
|
||||
description: the ids of those failed runs, only for the item named by failed_ids_kind and failed_ids_path
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
format: uuid
|
||||
runs:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
format: uuid
|
||||
status:
|
||||
$ref: "#/components/schemas/RecentRunStatus"
|
||||
ran_at:
|
||||
description: when the run started, or was created for one that has not reported a start
|
||||
type: string
|
||||
format: date-time
|
||||
duration_ms:
|
||||
type: integer
|
||||
required: [id, status, ran_at]
|
||||
required: [path, kind, status, failed_runs, runs]
|
||||
required:
|
||||
- window_hours
|
||||
- capped
|
||||
- total_runs
|
||||
- failed_runs
|
||||
- failing_items
|
||||
- running_items
|
||||
- items
|
||||
|
||||
/w/{workspace}/jobs/list:
|
||||
get:
|
||||
summary: list all jobs
|
||||
@@ -33319,6 +33497,11 @@ components:
|
||||
- auto_kind
|
||||
- has_preprocessor
|
||||
|
||||
RecentRunStatus:
|
||||
description: a failure someone or something marked as handled is `resolved`, not `failure`
|
||||
type: string
|
||||
enum: [success, failure, resolved, canceled, running]
|
||||
|
||||
ScriptLang:
|
||||
type: string
|
||||
enum: [
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
//! The provider config of AI agent and AI decision steps, checked against the workspace's
|
||||
//! AI provider resources before a flow is written.
|
||||
//!
|
||||
//! The catalog of those resources and the models each serves is the chat's own
|
||||
//! (`chat/flow/aiAgentProviderCatalog.ts`): its prompt needs it anyway, and it lists each
|
||||
//! resource's models through the provider. The chat sends it when a call needs it. An MCP
|
||||
//! client gets one built here from the resources and the AI settings alone, without model
|
||||
//! listings, so it can rule out a malformed or unknown provider but never a model id.
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use super::chat::Effect;
|
||||
use super::{array, truthy, Ctx, Surface};
|
||||
|
||||
#[derive(Deserialize, Clone, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct Catalog {
|
||||
#[serde(default)]
|
||||
options: Vec<ProviderOption>,
|
||||
/// `options` holds every AI provider resource of the workspace: one missing from it is
|
||||
/// not a resource at all.
|
||||
#[serde(default)]
|
||||
resources_are_complete: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ProviderOption {
|
||||
kind: String,
|
||||
resource_ref: String,
|
||||
models: Models,
|
||||
/// The models came from the endpoint's own listing, not a fallback.
|
||||
models_are_live: bool,
|
||||
/// The resource points at a gateway that may serve ids its listing omits.
|
||||
custom_endpoint: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Clone, Default)]
|
||||
struct Models {
|
||||
ids: Vec<String>,
|
||||
complete: bool,
|
||||
}
|
||||
|
||||
/// The kinds that serve decision models only, which an AI agent step cannot run on.
|
||||
const DECISION_ONLY_KINDS: &[&str] = &["typesafe", "cloudflare"];
|
||||
/// The model of OpenAI's Decisions API, the one kind both step types run on.
|
||||
const OPENAI_DECISION_MODEL: &str = "gpt-6-luna";
|
||||
const DECISION_PROVIDER_KINDS: &[&str] = &["typesafe", "cloudflare", "openai"];
|
||||
const MAX_PROMPTED_MODELS: usize = 25;
|
||||
const PROVIDER_SHAPE: &str = r#"{ "type": "static", "value": { "kind": "<provider kind>", "resource": "$res:<resource path>", "model": "<model id>" } }"#;
|
||||
|
||||
/// Every AI agent and AI decision module of a module tree, agent tools included, in the
|
||||
/// order the editor's `forEachAiAgentModule` visits them.
|
||||
fn for_each_ai_module<'a>(modules: &'a Value, f: &mut impl FnMut(&'a Value, &'a Value)) {
|
||||
for module in array(Some(modules)) {
|
||||
let Some(value) = module.get("value") else {
|
||||
continue;
|
||||
};
|
||||
match value.get("type").and_then(Value::as_str) {
|
||||
Some("aiagent") => {
|
||||
f(module, value);
|
||||
if let Some(tools) = value.get("tools") {
|
||||
for_each_ai_module(tools, f);
|
||||
}
|
||||
}
|
||||
Some("forloopflow" | "whileloopflow") => {
|
||||
if let Some(inner) = value.get("modules") {
|
||||
for_each_ai_module(inner, f);
|
||||
}
|
||||
}
|
||||
Some("aidecision") => f(module, value),
|
||||
Some(kind @ ("branchone" | "branchall")) => {
|
||||
if kind == "branchone" {
|
||||
if let Some(default) = value.get("default") {
|
||||
for_each_ai_module(default, f);
|
||||
}
|
||||
}
|
||||
for branch in array(value.get("branches")) {
|
||||
if let Some(inner) = branch.get("modules") {
|
||||
for_each_ai_module(inner, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A step's own static provider: what the catalog checks.
|
||||
fn static_provider(value: &Value) -> Option<&Value> {
|
||||
if truthy(value.get("agent")) {
|
||||
return None;
|
||||
}
|
||||
let transform = value.get("input_transforms")?.get("provider")?;
|
||||
(transform.get("type").and_then(Value::as_str) == Some("static")).then_some(transform)
|
||||
}
|
||||
|
||||
/// The `$res:` references the steps' providers use, or `None` when no step states a provider
|
||||
/// of its own and the catalog is not needed.
|
||||
fn provider_refs(modules: &Value) -> Option<Vec<String>> {
|
||||
let mut needed = false;
|
||||
let mut refs: Vec<String> = Vec::new();
|
||||
for_each_ai_module(modules, &mut |_, value| {
|
||||
let Some(transform) = static_provider(value) else {
|
||||
return;
|
||||
};
|
||||
needed = true;
|
||||
if let Some(resource) = transform
|
||||
.get("value")
|
||||
.and_then(|v| v.get("resource"))
|
||||
.and_then(Value::as_str)
|
||||
{
|
||||
if !refs.iter().any(|r| r == resource) {
|
||||
refs.push(resource.to_string());
|
||||
}
|
||||
}
|
||||
});
|
||||
needed.then_some(refs)
|
||||
}
|
||||
|
||||
/// What the catalog for `modules` is: none needed, the one to check against, or none yet
|
||||
/// because the chat has to send it first.
|
||||
pub(super) enum CatalogFor {
|
||||
NotNeeded,
|
||||
Ready(Catalog),
|
||||
Requested,
|
||||
}
|
||||
|
||||
pub(super) async fn catalog_for(ctx: &Ctx<'_>, modules: &Value) -> CatalogFor {
|
||||
let Some(resource_refs) = provider_refs(modules) else {
|
||||
return CatalogFor::NotNeeded;
|
||||
};
|
||||
match ctx.surface {
|
||||
Surface::Chat => match ctx.chat.and_then(|chat| chat.ai_provider_catalog.clone()) {
|
||||
Some(catalog) => CatalogFor::Ready(catalog),
|
||||
None => {
|
||||
ctx.effect(Effect::NeedsAiProviderCatalog { resource_refs });
|
||||
CatalogFor::Requested
|
||||
}
|
||||
},
|
||||
Surface::Mcp => CatalogFor::Ready(listed_catalog(ctx).await),
|
||||
}
|
||||
}
|
||||
|
||||
/// The resource types an AI agent or AI decision step's provider can be, as the editor lists
|
||||
/// them (`AI_PROVIDERS` and `DECISION_AI_PROVIDERS` in `copilot/lib.ts`).
|
||||
const AI_RESOURCE_TYPES: &[&str] = &[
|
||||
"openai",
|
||||
"anthropic",
|
||||
"googleai",
|
||||
"azure_openai",
|
||||
"azure_foundry",
|
||||
"mistral",
|
||||
"deepseek",
|
||||
"groq",
|
||||
"openrouter",
|
||||
"togetherai",
|
||||
"aws_bedrock",
|
||||
"customai",
|
||||
"typesafe",
|
||||
"cloudflare",
|
||||
];
|
||||
const MAX_PROVIDER_RESOURCES: usize = 8;
|
||||
|
||||
/// The workspace's AI provider resources, without model listings: each one's models are the
|
||||
/// ones its AI settings configure, which can never rule an id out.
|
||||
async fn listed_catalog(ctx: &Ctx<'_>) -> Catalog {
|
||||
let route = ctx.ws(&format!(
|
||||
"resources/list?resource_type={}",
|
||||
AI_RESOURCE_TYPES.join(",")
|
||||
));
|
||||
let (resources, listed_all) = match ctx.get(&route).await {
|
||||
Ok(resources) => (resources, true),
|
||||
Err(_) => (json!([]), false),
|
||||
};
|
||||
let config = ctx
|
||||
.get(&ctx.ws("workspaces/get_copilot_info"))
|
||||
.await
|
||||
.unwrap_or(Value::Null);
|
||||
let providers = config.get("providers").and_then(Value::as_object);
|
||||
let configured = |path: &str| {
|
||||
providers
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find(|(_, p)| p.get("resource_path").and_then(Value::as_str) == Some(path))
|
||||
.map(|(kind, p)| (kind.clone(), p))
|
||||
};
|
||||
let default_kind = config
|
||||
.get("default_model")
|
||||
.and_then(|m| m.get("provider"))
|
||||
.and_then(Value::as_str);
|
||||
let mut candidates: Vec<(String, String)> = array(Some(&resources))
|
||||
.iter()
|
||||
.filter_map(|r| {
|
||||
let kind = r.get("resource_type")?.as_str()?;
|
||||
let path = r.get("path")?.as_str()?;
|
||||
AI_RESOURCE_TYPES
|
||||
.contains(&kind)
|
||||
.then(|| (kind.to_string(), path.to_string()))
|
||||
})
|
||||
.collect();
|
||||
let rank = |(kind, path): &(String, String)| match configured(path) {
|
||||
None => 2,
|
||||
Some(_) if Some(kind.as_str()) == default_kind => 0,
|
||||
Some(_) => 1,
|
||||
};
|
||||
candidates.sort_by(|a, b| rank(a).cmp(&rank(b)).then_with(|| a.1.cmp(&b.1)));
|
||||
let complete = listed_all && candidates.len() <= MAX_PROVIDER_RESOURCES;
|
||||
let options = candidates
|
||||
.into_iter()
|
||||
.take(MAX_PROVIDER_RESOURCES)
|
||||
.map(|(kind, path)| {
|
||||
let ids = configured(&path)
|
||||
.map(|(_, p)| {
|
||||
array(p.get("models"))
|
||||
.iter()
|
||||
.filter_map(|m| m.as_str().map(String::from))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
ProviderOption {
|
||||
kind,
|
||||
resource_ref: format!("$res:{path}"),
|
||||
models: Models { ids, complete: false },
|
||||
models_are_live: false,
|
||||
custom_endpoint: true,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Catalog { options, resources_are_complete: complete }
|
||||
}
|
||||
|
||||
struct Issue {
|
||||
message: String,
|
||||
blocking: bool,
|
||||
/// The catalog established it rather than failing to rule it out.
|
||||
settled: bool,
|
||||
}
|
||||
|
||||
fn blocking(message: String) -> Option<Issue> {
|
||||
Some(Issue { message, blocking: true, settled: false })
|
||||
}
|
||||
|
||||
fn rules_out_other_models(option: &ProviderOption) -> bool {
|
||||
option.models_are_live && option.models.complete && !option.custom_endpoint
|
||||
}
|
||||
|
||||
fn check_provider(value: Option<&Value>, catalog: &Catalog, step_type: &str) -> Option<Issue> {
|
||||
let provider = match value {
|
||||
Some(Value::String(reference)) => {
|
||||
return blocking(format!(
|
||||
"provider must be an object {PROVIDER_SHAPE}, not the resource reference string {}",
|
||||
json!(reference)
|
||||
))
|
||||
}
|
||||
Some(Value::Object(provider)) => provider,
|
||||
_ => return blocking(format!("provider must be an object {PROVIDER_SHAPE}")),
|
||||
};
|
||||
let text = |key: &str| {
|
||||
provider
|
||||
.get(key)
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let (kind, resource, model) = (text("kind"), text("resource"), text("model"));
|
||||
if kind.is_empty() {
|
||||
return blocking(format!(
|
||||
"provider.kind is missing. Expected {PROVIDER_SHAPE}"
|
||||
));
|
||||
}
|
||||
if step_type == "aidecision" && !DECISION_PROVIDER_KINDS.contains(&kind) {
|
||||
return blocking(format!("an AI decision step runs on a decision model: provider.kind must be \"typesafe\", \"cloudflare\" or \"openai\", not \"{kind}\""));
|
||||
}
|
||||
if step_type != "aidecision" && DECISION_ONLY_KINDS.contains(&kind) {
|
||||
return blocking(format!("\"{kind}\" serves decision models, which answer typed questions rather than messages: use an \"aidecision\" step rather than an AI agent"));
|
||||
}
|
||||
if !resource.starts_with("$res:") {
|
||||
return blocking(format!(
|
||||
"provider.resource must be a \"$res:<resource path>\" reference. Expected {PROVIDER_SHAPE}"
|
||||
));
|
||||
}
|
||||
if model.is_empty() {
|
||||
return blocking(format!(
|
||||
"provider.model is missing. Expected {PROVIDER_SHAPE}"
|
||||
));
|
||||
}
|
||||
if catalog.options.is_empty() {
|
||||
return catalog.resources_are_complete.then(|| Issue {
|
||||
message: format!("this workspace has no AI provider resources, so \"{resource}\" cannot resolve and the step cannot run. Tell the user to create an AI provider resource (Anthropic, OpenAI, ...) and rewrite the step against it."),
|
||||
blocking: false,
|
||||
settled: true,
|
||||
});
|
||||
}
|
||||
let Some(found) = catalog.options.iter().find(|o| o.resource_ref == resource) else {
|
||||
return Some(Issue {
|
||||
message: format!(
|
||||
"provider.resource \"{resource}\" is not one of this workspace's AI provider resources"
|
||||
),
|
||||
blocking: catalog.resources_are_complete,
|
||||
settled: false,
|
||||
});
|
||||
};
|
||||
if found.kind != kind {
|
||||
return blocking(format!(
|
||||
"provider.kind \"{kind}\" does not match \"{resource}\", which is a `{}` resource",
|
||||
found.kind
|
||||
));
|
||||
}
|
||||
// An OpenAI resource lists its chat models, which says nothing about its decision model.
|
||||
if step_type == "aidecision" && kind == "openai" {
|
||||
return (model != OPENAI_DECISION_MODEL).then(|| Issue {
|
||||
message: format!("model \"{model}\" is not the model OpenAI's Decisions API is known to serve, \"{OPENAI_DECISION_MODEL}\""),
|
||||
blocking: false,
|
||||
settled: false,
|
||||
});
|
||||
}
|
||||
if found.models_are_live && !found.models.ids.iter().any(|id| id == model) {
|
||||
return Some(Issue {
|
||||
message: format!("model \"{model}\" is not in the model listing of \"{resource}\""),
|
||||
blocking: rules_out_other_models(found),
|
||||
settled: false,
|
||||
});
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn describe_option(option: &ProviderOption) -> String {
|
||||
let shown = &option.models.ids[..option.models.ids.len().min(MAX_PROMPTED_MODELS)];
|
||||
let more = if option.models.ids.len() > shown.len() {
|
||||
format!(", ... ({} more)", option.models.ids.len() - shown.len())
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let caveat = if !option.models_are_live {
|
||||
" (the endpoint would not list its models, so these are a guess — confirm the id with the user)"
|
||||
} else if !rules_out_other_models(option) {
|
||||
" (the endpoint may also serve model names this list does not show)"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let models = if shown.is_empty() {
|
||||
"none listed".to_string()
|
||||
} else {
|
||||
format!("{}{more}{caveat}", shown.join(", "))
|
||||
};
|
||||
format!(
|
||||
"- `{}` (kind `{}`) — models: {models}",
|
||||
option.resource_ref, option.kind
|
||||
)
|
||||
}
|
||||
|
||||
/// Refuse a provider config that would fail at run time, and report in `warnings` what the
|
||||
/// catalog could not establish, so an incomplete catalog never rejects a provider that works.
|
||||
pub(super) fn validate(
|
||||
modules: &Value,
|
||||
catalog: Option<&Catalog>,
|
||||
warnings: &mut Vec<String>,
|
||||
) -> Result<(), String> {
|
||||
let empty = Catalog::default();
|
||||
let catalog = catalog.unwrap_or(&empty);
|
||||
let mut errors = Vec::new();
|
||||
for_each_ai_module(modules, &mut |module, value| {
|
||||
let Some(transform) = static_provider(value) else {
|
||||
return;
|
||||
};
|
||||
let step_type = value
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
let Some(issue) = check_provider(transform.get("value"), catalog, step_type) else {
|
||||
return;
|
||||
};
|
||||
let id = module.get("id").and_then(Value::as_str).unwrap_or_default();
|
||||
if issue.blocking {
|
||||
errors.push(format!("Step \"{id}\": {}", issue.message));
|
||||
} else if issue.settled {
|
||||
warnings.push(format!("Step \"{id}\": {}", issue.message));
|
||||
} else {
|
||||
warnings.push(format!("Step \"{id}\": {}, which could not be ruled out. Confirm it with the user if the step fails to run.", issue.message));
|
||||
}
|
||||
});
|
||||
if errors.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let hint = if catalog.options.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(
|
||||
"\nAI provider resources in this workspace:\n{}",
|
||||
catalog
|
||||
.options
|
||||
.iter()
|
||||
.map(describe_option)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
)
|
||||
};
|
||||
Err(format!(
|
||||
"Invalid AI agent provider configuration:\n{}{hint}",
|
||||
errors.join("\n")
|
||||
))
|
||||
}
|
||||
|
||||
/// The tool-result suffix for provider findings that did not block the write.
|
||||
pub(super) fn format_warnings(warnings: &[String]) -> String {
|
||||
if warnings.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
format!("\n\nAI agent provider warnings:\n{}", warnings.join("\n"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn agent(model: &str) -> Value {
|
||||
json!([{ "id": "a", "value": { "type": "aiagent", "input_transforms": { "provider": {
|
||||
"type": "static",
|
||||
"value": { "kind": "openai", "resource": "$res:u/x/oai", "model": model }
|
||||
} } } }])
|
||||
}
|
||||
|
||||
fn catalog(models_are_live: bool) -> Catalog {
|
||||
serde_json::from_value(json!({
|
||||
"resourcesAreComplete": true,
|
||||
"options": [{
|
||||
"kind": "openai", "resourceRef": "$res:u/x/oai", "modelsAreLive": models_are_live,
|
||||
"customEndpoint": false, "models": { "ids": ["gpt-a"], "complete": true }
|
||||
}]
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_live_complete_listing_rules_out_a_model() {
|
||||
let mut warnings = vec![];
|
||||
assert!(validate(&agent("gpt-z"), Some(&catalog(true)), &mut warnings).is_err());
|
||||
|
||||
assert!(validate(&agent("gpt-z"), Some(&catalog(false)), &mut warnings).is_ok());
|
||||
assert!(validate(&agent("gpt-z"), None, &mut warnings).is_ok());
|
||||
assert!(validate(&agent("gpt-a"), Some(&catalog(true)), &mut warnings).is_ok());
|
||||
assert!(warnings.is_empty());
|
||||
}
|
||||
}
|
||||
+248
-82
@@ -7,17 +7,16 @@ use std::sync::LazyLock;
|
||||
use serde_json::{json, Map, Value};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use super::runs::finish_run;
|
||||
use super::runs::{finish_run, run_tool, start_run, Resolved, RunTarget};
|
||||
use super::workspace::{
|
||||
api_message, app_source_to_draft_value, deployed_item_exists, find_and_replace, get_deployed,
|
||||
get_draft, item_exists, normalize_app_draft, path_enc, persist_draft, Persist,
|
||||
get_draft, item_exists, normalize_app_draft, persist_draft, Persist,
|
||||
};
|
||||
use super::{
|
||||
bool_arg, js_head, js_len, matches_glob, opt_str_arg, pretty, str_arg, truthy, Ctx, ToolResult,
|
||||
bool_arg, js_head, js_len, matches_glob, opt_str_arg, pretty, put, str_arg, truthy, Ctx,
|
||||
ToolResult,
|
||||
};
|
||||
|
||||
// `init_app` is dispatched below but stays out of this list until `gen/app_templates.json`
|
||||
// is emitted by the generator.
|
||||
pub(super) const TOOLS: &[&str] = &[
|
||||
"init_app",
|
||||
"read_app_file",
|
||||
@@ -214,23 +213,28 @@ async fn load_app(ctx: &Ctx<'_>, path: &str) -> Result<Loaded, String> {
|
||||
Ok(Loaded { value: app_source_to_draft_value(&app, Some(&app)), last_sync })
|
||||
}
|
||||
|
||||
/// What the backend requires of a draft from an operator with builder rights: sandboxed,
|
||||
/// never in viewer mode, and running as nobody but its builder.
|
||||
async fn conform_builder_policy(ctx: &Ctx<'_>, value: &mut Value) {
|
||||
/// Whether the caller's role composes apps out of deployed runnables. They can save no inline
|
||||
/// runnable.
|
||||
async fn builds_apps(ctx: &Ctx<'_>) -> bool {
|
||||
if !ctx.auth.is_operator {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
let Ok(memberships) = ctx.get("/workspaces/users").await else {
|
||||
return;
|
||||
return false;
|
||||
};
|
||||
let builder = memberships
|
||||
memberships
|
||||
.get("workspaces")
|
||||
.and_then(Value::as_array)
|
||||
.and_then(|list| list.iter().find(|w| text_of(w, "id") == Some(ctx.w_id)))
|
||||
.and_then(|w| w.get("operator_settings"))
|
||||
.and_then(|s| s.get("builder_apps"))
|
||||
== Some(&Value::Bool(true));
|
||||
if !builder {
|
||||
.and_then(|w| w.get("capabilities"))
|
||||
.and_then(|c| text_of(c, "apps"))
|
||||
== Some("compose")
|
||||
}
|
||||
|
||||
/// What the backend requires of a draft from a role that composes apps: sandboxed,
|
||||
/// never in viewer mode, and running as nobody but its builder.
|
||||
async fn conform_builder_policy(ctx: &Ctx<'_>, value: &mut Value) {
|
||||
if !builds_apps(ctx).await {
|
||||
return;
|
||||
}
|
||||
let policy = object_mut(value, "policy");
|
||||
@@ -272,11 +276,13 @@ async fn save_app(
|
||||
let mut out = Map::new();
|
||||
out.insert("success".into(), json!(true));
|
||||
out.insert("message".into(), json!(message));
|
||||
out.insert(
|
||||
"preview_url".into(),
|
||||
json!(ctx.page_url(&format!(
|
||||
put(
|
||||
&mut out,
|
||||
"preview_url",
|
||||
ctx.link(&format!(
|
||||
"/apps_raw/edit/{path}?view=preview&nomenubar=true"
|
||||
))),
|
||||
))
|
||||
.map(Value::from),
|
||||
);
|
||||
if let Some(warning) = warning {
|
||||
out.insert("warning".into(), json!(warning));
|
||||
@@ -390,9 +396,6 @@ fn app_table_ref(datatable: &str, schema: Option<&str>, reference: &str) -> Stri
|
||||
async fn init_app(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
let path = str_arg(args, "path")?;
|
||||
let framework = str_arg(args, "framework")?;
|
||||
let template = APP_TEMPLATES["templates"]
|
||||
.get(framework)
|
||||
.ok_or_else(|| format!("Invalid framework \"{framework}\""))?;
|
||||
|
||||
if get_draft(ctx, "raw_app", path).await?.is_some() {
|
||||
return Err(format!(
|
||||
@@ -405,13 +408,28 @@ async fn init_app(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
));
|
||||
}
|
||||
|
||||
ctx.status(format!(
|
||||
"Saving app \"{path}\" draft ({framework} template)…"
|
||||
));
|
||||
// A builder can save no inline runnable, so they start from a static page instead of the tour.
|
||||
let builder = builds_apps(ctx).await;
|
||||
let template = APP_TEMPLATES[if builder {
|
||||
"builder_templates"
|
||||
} else {
|
||||
"templates"
|
||||
}]
|
||||
.get(framework)
|
||||
.ok_or_else(|| format!("Invalid framework \"{framework}\""))?;
|
||||
let starters = &APP_TEMPLATES["starter_runnables"];
|
||||
let mut value = Map::new();
|
||||
if let Some(summary) = opt_str_arg(args, "summary") {
|
||||
value.insert("summary".into(), json!(summary));
|
||||
}
|
||||
value.insert("files".into(), template.clone());
|
||||
value.insert("runnables".into(), starters.clone());
|
||||
value.insert(
|
||||
"runnables".into(),
|
||||
if builder { json!({}) } else { starters.clone() },
|
||||
);
|
||||
value.insert("policy".into(), json!({ "sandbox": true }));
|
||||
let data = args.get("data").filter(|d| truthy(Some(d)));
|
||||
let schema = data.and_then(|d| text_of(d, "schema"));
|
||||
@@ -449,9 +467,23 @@ async fn init_app(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
Some(schema) => format!(" Its data config names schema \"{schema}\" of data table \"{datatable}\" without creating it: if it does not exist yet, create it before the tables that go in it."),
|
||||
None => String::new(),
|
||||
};
|
||||
let start = if builder {
|
||||
"The template is a static page with no runnables: replace its UI, and add only deployed scripts and flows, by path.".to_string()
|
||||
} else {
|
||||
format!("The template is a demo tour with starter runnables {}: replace its UI and delete the runnables the app does not need (delete_app_runnable).", starter_keys.join(", "))
|
||||
};
|
||||
// The chat opens the app in its own panel; an MCP client only has the link.
|
||||
let open_preview = if ctx.link("/").is_some() {
|
||||
" Open preview_url in a browser the user can see from this conversation if you have one, and otherwise give them the link: its live preview follows every later edit."
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let message = format!(
|
||||
"Initialized a per-user draft app \"{path}\" from the {framework} template (saved server-side, not a deployed workspace item). The template is a demo tour with starter runnables {}: replace its UI and delete the runnables the app does not need (delete_app_runnable). Use write_app_file / write_app_runnable to evolve it.{data_note} Open preview_url in a browser the user can see from this conversation if you have one, and otherwise give them the link: its live preview follows every later edit.",
|
||||
starter_keys.join(", ")
|
||||
"Initialized a per-user draft app \"{path}\" from the {framework} template (saved server-side, not a deployed workspace item). {start} Use write_app_file / write_app_runnable to evolve it.{data_note}{open_preview}"
|
||||
);
|
||||
ctx.status_after_save(
|
||||
format!("Saved app \"{path}\" draft ({framework})"),
|
||||
Some("Saved as draft"),
|
||||
);
|
||||
save_app(ctx, path, value, None, message, None).await
|
||||
}
|
||||
@@ -507,6 +539,7 @@ async fn read_app_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
inline_runnable_content(&value, key, extension, path)?.0
|
||||
}
|
||||
};
|
||||
ctx.status(format!("Read {}", target.file_path()));
|
||||
let int = |name: &str| args.get(name).and_then(Value::as_i64);
|
||||
Ok(format_file_read(content, int("offset"), int("limit")))
|
||||
}
|
||||
@@ -565,7 +598,7 @@ fn search_files(
|
||||
query: &str,
|
||||
file_glob: Option<&str>,
|
||||
max_matches: i64,
|
||||
) -> String {
|
||||
) -> (String, usize, usize) {
|
||||
let needle = query.to_lowercase();
|
||||
files.sort_by(|a, b| locale_compare(&a.0, &b.0));
|
||||
if let Some(glob) = file_glob {
|
||||
@@ -601,7 +634,7 @@ fn search_files(
|
||||
}
|
||||
|
||||
if total == 0 {
|
||||
return format!(
|
||||
let text = format!(
|
||||
"No matches. Try a broader or differently-spelled term{}.",
|
||||
if file_glob.is_some() {
|
||||
", or drop the file_glob"
|
||||
@@ -609,6 +642,7 @@ fn search_files(
|
||||
""
|
||||
}
|
||||
);
|
||||
return (text, 0, 0);
|
||||
}
|
||||
|
||||
let plural = |n: usize, one: &str, many: &str| {
|
||||
@@ -665,7 +699,7 @@ fn search_files(
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
out.join("\n")
|
||||
(out.join("\n"), total, file_count)
|
||||
}
|
||||
|
||||
async fn search_app(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
@@ -681,12 +715,18 @@ async fn search_app(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
.unwrap_or(SEARCH_DEFAULT_MAX_MATCHES)
|
||||
.min(SEARCH_MAX_MATCHES_CEILING);
|
||||
let file_glob = opt_str_arg(args, "file_glob").filter(|glob| !glob.is_empty());
|
||||
Ok(search_files(
|
||||
searchable_files(&value),
|
||||
query,
|
||||
file_glob,
|
||||
max_matches,
|
||||
))
|
||||
let (text, total, files) =
|
||||
search_files(searchable_files(&value), query, file_glob, max_matches);
|
||||
ctx.status(if total == 0 {
|
||||
format!("No matches for \"{query}\"")
|
||||
} else {
|
||||
format!(
|
||||
"Found {total} match{} in {files} file{}",
|
||||
if total == 1 { "" } else { "es" },
|
||||
if files == 1 { "" } else { "s" }
|
||||
)
|
||||
});
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -702,6 +742,16 @@ async fn write_app_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
assert_not_generated(&file_path)?;
|
||||
|
||||
let Loaded { mut value, last_sync } = load_app(ctx, path).await?;
|
||||
let before = value
|
||||
.get("files")
|
||||
.and_then(|files| text_of(files, &file_path))
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
ctx.file_diff(&before, content, &file_path, &file_path);
|
||||
ctx.status_after_save(
|
||||
format!("Updated {file_path} in app \"{path}\""),
|
||||
Some("Saved as draft"),
|
||||
);
|
||||
object_mut(&mut value, "files").insert(file_path.clone(), json!(content));
|
||||
let message = format!("Updated draft app \"{path}\" with frontend file \"{file_path}\".");
|
||||
save_app(ctx, path, value, last_sync.as_deref(), message, None).await
|
||||
@@ -715,14 +765,21 @@ async fn delete_app_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
assert_not_generated(&file_path)?;
|
||||
|
||||
let Loaded { mut value, last_sync } = load_app(ctx, path).await?;
|
||||
if object_mut(&mut value, "files")
|
||||
.shift_remove(&file_path)
|
||||
.is_none()
|
||||
{
|
||||
let Some(removed) = object_mut(&mut value, "files").shift_remove(&file_path) else {
|
||||
return Err(format!(
|
||||
"Frontend file \"{file_path}\" not found in app \"{path}\"."
|
||||
));
|
||||
}
|
||||
};
|
||||
ctx.file_diff(
|
||||
removed.as_str().unwrap_or_default(),
|
||||
"",
|
||||
&file_path,
|
||||
&file_path,
|
||||
);
|
||||
ctx.status_after_save(
|
||||
format!("Removed {file_path} from app \"{path}\""),
|
||||
Some("Saved as draft"),
|
||||
);
|
||||
let message = format!("Removed \"{file_path}\" from draft app \"{path}\".");
|
||||
save_app(ctx, path, value, last_sync.as_deref(), message, None).await
|
||||
}
|
||||
@@ -748,11 +805,14 @@ async fn patch_app_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
format!("Frontend file \"{file_path}\" not found in app \"{path}\".")
|
||||
})?;
|
||||
let updated = find_and_replace(current, old, new, replace_all, &label)?;
|
||||
ctx.file_diff(current, &updated, file_path, file_path);
|
||||
object_mut(&mut value, "files").insert(file_path.clone(), json!(updated));
|
||||
}
|
||||
Target::Backend { key, extension, .. } => {
|
||||
let (current, runnable) = inline_runnable_content(&value, key, extension, path)?;
|
||||
let updated = find_and_replace(current, old, new, replace_all, &label)?;
|
||||
let file_path = target.file_path();
|
||||
ctx.file_diff(current, &updated, &file_path, &file_path);
|
||||
let language = runnable
|
||||
.get("inlineScript")
|
||||
.and_then(|s| s.get("language"))
|
||||
@@ -764,6 +824,10 @@ async fn patch_app_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
object_mut(&mut value, "runnables").insert(key.clone(), runnable);
|
||||
}
|
||||
}
|
||||
ctx.status_after_save(
|
||||
format!("Patched {} in app \"{path}\"", target.file_path()),
|
||||
Some("Saved as draft"),
|
||||
);
|
||||
let message = format!(
|
||||
"Patched \"{}\" in draft app \"{path}\".",
|
||||
target.file_path()
|
||||
@@ -782,7 +846,11 @@ fn build_persisted_runnable(input: &Value, existing: Option<&Value>) -> Result<V
|
||||
let name = str_arg(input, "name")?;
|
||||
let kind = str_arg(input, "type")?;
|
||||
let existing = existing.and_then(Value::as_object);
|
||||
let fields = match input.get("staticInputs").and_then(Value::as_object) {
|
||||
let static_inputs = input.get("staticInputs").and_then(Value::as_object);
|
||||
// An agent runnable takes every input from the app: a static one inherited from the kind it
|
||||
// was converted from would be pinned by the deployed policy over every viewer's message.
|
||||
let fields = match static_inputs {
|
||||
_ if kind == "agent" => json!({}),
|
||||
Some(static_inputs) => Value::Object(
|
||||
static_inputs
|
||||
.iter()
|
||||
@@ -828,9 +896,16 @@ fn build_persisted_runnable(input: &Value, existing: Option<&Value>) -> Result<V
|
||||
return Ok(Value::Object(out));
|
||||
}
|
||||
|
||||
let path = text_of(input, "path")
|
||||
.filter(|p| !p.is_empty())
|
||||
.ok_or("path is required when runnable type is \"script\", \"flow\", or \"hubscript\".")?;
|
||||
let path = text_of(input, "path").filter(|p| !p.is_empty()).ok_or(
|
||||
"path is required when runnable type is \"script\", \"flow\", \"hubscript\" or \"agent\".",
|
||||
)?;
|
||||
// A static input is pinned by the deployed policy: every viewer's turn would send the same one.
|
||||
if kind == "agent" && static_inputs.is_some_and(|inputs| !inputs.is_empty()) {
|
||||
return Err(
|
||||
"An \"agent\" runnable takes no staticInputs: each turn's inputs come from the app."
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
let same_target = existing.is_some_and(|e| {
|
||||
matches!(
|
||||
e.get("type").and_then(Value::as_str),
|
||||
@@ -852,6 +927,45 @@ fn build_persisted_runnable(input: &Value, existing: Option<&Value>) -> Result<V
|
||||
Ok(Value::Object(out))
|
||||
}
|
||||
|
||||
/// An inline runnable's code; none for one that names a workspace or hub item.
|
||||
fn inline_code(runnable: Option<&Value>) -> Option<&str> {
|
||||
let runnable = runnable?;
|
||||
matches!(text_of(runnable, "type"), Some("inline" | "runnableByName")).then(|| {
|
||||
runnable
|
||||
.get("inlineScript")
|
||||
.and_then(|s| text_of(s, "content"))
|
||||
.unwrap_or_default()
|
||||
})
|
||||
}
|
||||
|
||||
/// The card's diff of a runnable's code. A runnable that references an item has no code
|
||||
/// of its own to diff.
|
||||
fn runnable_diff(ctx: &Ctx<'_>, key: &str, before: Option<&Value>, after: Option<&Value>) {
|
||||
let (before_code, after_code) = (inline_code(before), inline_code(after));
|
||||
if (before_code.is_none() && after_code.is_none()) || (after.is_some() && after_code.is_none())
|
||||
{
|
||||
return;
|
||||
}
|
||||
let file = |runnable: Option<&Value>| {
|
||||
format!(
|
||||
"backend/{key}/main.{}",
|
||||
runnable.map_or("ts", inline_extension)
|
||||
)
|
||||
};
|
||||
let after_file = file(after.or(before));
|
||||
let before_file = if before_code.is_none() {
|
||||
after_file.clone()
|
||||
} else {
|
||||
file(before)
|
||||
};
|
||||
ctx.file_diff(
|
||||
before_code.unwrap_or_default(),
|
||||
after_code.unwrap_or_default(),
|
||||
&after_file,
|
||||
&before_file,
|
||||
);
|
||||
}
|
||||
|
||||
/// Whether the script or flow a path runnable names is deployed. None when it names
|
||||
/// neither, or the probe failed: the answer only annotates a write.
|
||||
async fn path_target_deployed(ctx: &Ctx<'_>, runnable: &Value) -> Option<bool> {
|
||||
@@ -871,6 +985,11 @@ async fn write_app_runnable(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
let Loaded { mut value, last_sync } = load_app(ctx, path).await?;
|
||||
let existing = value.get("runnables").and_then(|r| r.get(key));
|
||||
let persisted = build_persisted_runnable(input, existing)?;
|
||||
runnable_diff(ctx, key, existing, Some(&persisted));
|
||||
ctx.status_after_save(
|
||||
format!("Updated runnable \"{key}\" in app \"{path}\""),
|
||||
Some("Saved as draft"),
|
||||
);
|
||||
let warning = match path_target_deployed(ctx, &persisted).await {
|
||||
Some(false) => Some(format!(
|
||||
"This runnable points at an item that is NOT deployed (\"{key}\" → {} \"{}\"), so it fails at runtime — a path runnable runs the deployed item, never a draft. Offer to deploy just that item with deploy_workspace_item; the app itself does not need deploying, since the preview runs its draft.",
|
||||
@@ -889,14 +1008,16 @@ async fn delete_app_runnable(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
let path = str_arg(args, "path")?;
|
||||
let key = str_arg(args, "key")?;
|
||||
let Loaded { mut value, last_sync } = load_app(ctx, path).await?;
|
||||
if object_mut(&mut value, "runnables")
|
||||
.shift_remove(key)
|
||||
.is_none()
|
||||
{
|
||||
let Some(removed) = object_mut(&mut value, "runnables").shift_remove(key) else {
|
||||
return Err(format!(
|
||||
"Backend runnable \"{key}\" not found in app \"{path}\"."
|
||||
));
|
||||
}
|
||||
};
|
||||
runnable_diff(ctx, key, Some(&removed), None);
|
||||
ctx.status_after_save(
|
||||
format!("Removed runnable \"{key}\" from app \"{path}\""),
|
||||
Some("Saved as draft"),
|
||||
);
|
||||
recompute_policy(&mut value);
|
||||
let message = format!("Removed runnable \"{key}\" from draft app \"{path}\".");
|
||||
save_app(ctx, path, value, last_sync.as_deref(), message, None).await
|
||||
@@ -907,7 +1028,12 @@ async fn delete_app_runnable(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// The `execute_component` body that runs a runnable the way the editor preview does.
|
||||
fn execute_component_body(app_path: &str, key: &str, runnable: &Value, args: &Value) -> Value {
|
||||
pub(super) fn execute_component_body(
|
||||
app_path: &str,
|
||||
key: &str,
|
||||
runnable: &Value,
|
||||
args: &Value,
|
||||
) -> Value {
|
||||
let fields = entries(runnable, "fields");
|
||||
let mut test_args = args.as_object().cloned().unwrap_or_default();
|
||||
let mut static_fields = Map::new();
|
||||
@@ -998,9 +1124,7 @@ fn execute_component_body(app_path: &str, key: &str, runnable: &Value, args: &Va
|
||||
Value::Object(body)
|
||||
}
|
||||
|
||||
async fn test_run_app_runnable(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
let path = str_arg(args, "path")?;
|
||||
let key = str_arg(args, "key")?;
|
||||
async fn resolve_app_runnable(ctx: &Ctx<'_>, path: &str, key: &str) -> Result<Resolved, String> {
|
||||
let value = load_app(ctx, path).await?.value;
|
||||
let runnables = entries(&value, "runnables");
|
||||
let Some(runnable) = runnables.get(key).filter(|r| truthy(Some(r))) else {
|
||||
@@ -1014,35 +1138,64 @@ async fn test_run_app_runnable(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
}
|
||||
));
|
||||
};
|
||||
|
||||
let body = execute_component_body(
|
||||
path,
|
||||
key,
|
||||
runnable,
|
||||
args.get("args").unwrap_or(&Value::Null),
|
||||
);
|
||||
let id = ctx
|
||||
.request(
|
||||
"POST",
|
||||
&ctx.ws(&format!("apps_u/execute_component/{}", path_enc(path))),
|
||||
Some(body),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
let message = api_message(&e);
|
||||
let message = if js_len(message) > MAX_TOOL_ERROR_LENGTH {
|
||||
format!("{}... (truncated)", js_head(message, MAX_TOOL_ERROR_LENGTH))
|
||||
} else {
|
||||
message.to_string()
|
||||
};
|
||||
format!("Failed to execute test run: {message}")
|
||||
})?;
|
||||
let id = id.trim().trim_matches('"').to_string();
|
||||
|
||||
// A path runnable aimed at a flow queues a flow job, whose steps are worth a look.
|
||||
let is_flow = text_of(runnable, "runType") == Some("flow");
|
||||
let label = format!("{path} / {key}");
|
||||
finish_run(ctx, Ok(id), &label, is_flow, "test", args).await
|
||||
Ok(Resolved {
|
||||
target: RunTarget::AppRunnable {
|
||||
app_path: path.to_string(),
|
||||
key: key.to_string(),
|
||||
runnable: runnable.clone(),
|
||||
},
|
||||
schema: None,
|
||||
code: None,
|
||||
lang: None,
|
||||
summary: None,
|
||||
runnable_kind: if is_flow { "flow" } else { "script" },
|
||||
start_message: format!("Running backend runnable \"{key}\" of app \"{path}\"..."),
|
||||
conversational: false,
|
||||
module: None,
|
||||
})
|
||||
}
|
||||
|
||||
async fn test_run_app_runnable(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
let path = str_arg(args, "path")?;
|
||||
let key = str_arg(args, "key")?;
|
||||
run_tool(
|
||||
ctx,
|
||||
args,
|
||||
resolve_app_runnable(ctx, path, key),
|
||||
async |resolved: Resolved| {
|
||||
let run_args = args
|
||||
.get("args")
|
||||
.and_then(Value::as_object)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let id = start_run(ctx, &resolved.target, run_args, &[])
|
||||
.await
|
||||
.map_err(|message| {
|
||||
let message = if js_len(&message) > MAX_TOOL_ERROR_LENGTH {
|
||||
format!(
|
||||
"{}... (truncated)",
|
||||
js_head(&message, MAX_TOOL_ERROR_LENGTH)
|
||||
)
|
||||
} else {
|
||||
message
|
||||
};
|
||||
format!("Failed to execute test run: {message}")
|
||||
})?;
|
||||
let label = format!("{path} / {key}");
|
||||
finish_run(
|
||||
ctx,
|
||||
Ok(id),
|
||||
&label,
|
||||
resolved.runnable_kind == "flow",
|
||||
"test",
|
||||
args,
|
||||
)
|
||||
.await
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1094,15 +1247,15 @@ mod tests {
|
||||
("/App.tsx".to_string(), "foo".to_string()),
|
||||
];
|
||||
assert_eq!(
|
||||
search_files(files.clone(), "foo", None, 100),
|
||||
search_files(files.clone(), "foo", None, 100).0,
|
||||
"3 matches in 2 files\n/App.tsx\n 1: foo\n/b.ts\n 1: one\n 2: Foo()\n 3: foo()\n 4: four\n 5: five"
|
||||
);
|
||||
assert_eq!(
|
||||
search_files(files.clone(), "foo", Some("*.ts"), 1),
|
||||
search_files(files.clone(), "foo", Some("*.ts"), 1).0,
|
||||
"2 matches in 1 file (showing the first 1; narrow with file_glob or a more specific query)\n/b.ts\n 1: one\n 2: Foo()\n 3: foo()\n 4: four"
|
||||
);
|
||||
assert_eq!(
|
||||
search_files(files, "nope", Some("*.ts"), 100),
|
||||
search_files(files, "nope", Some("*.ts"), 100).0,
|
||||
"No matches. Try a broader or differently-spelled term, or drop the file_glob."
|
||||
);
|
||||
}
|
||||
@@ -1137,6 +1290,19 @@ mod tests {
|
||||
.unwrap();
|
||||
assert_eq!(retargeted["schema"], json!({}));
|
||||
|
||||
let agent = build_persisted_runnable(
|
||||
&json!({ "name": "n", "type": "agent", "path": "u/a/agent" }),
|
||||
Some(&existing),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(agent["runType"], "agent");
|
||||
assert_eq!(agent["fields"], json!({}));
|
||||
assert!(build_persisted_runnable(
|
||||
&json!({ "name": "n", "type": "agent", "path": "u/a/agent", "staticInputs": { "m": 1 } }),
|
||||
None,
|
||||
)
|
||||
.is_err());
|
||||
|
||||
let inline = build_persisted_runnable(
|
||||
&json!({
|
||||
"name": "n", "type": "inline", "staticInputs": { "y": 2 },
|
||||
@@ -0,0 +1,308 @@
|
||||
//! What the in-app chat sends beside a tool call, and what it gets back to apply in the
|
||||
//! browser. MCP has neither: its tools read and write the server alone.
|
||||
|
||||
use axum::{extract::Path, routing::post, Extension, Json, Router};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value};
|
||||
use windmill_api_auth::is_effectively_unscoped;
|
||||
use windmill_common::error::{Error, JsonResult};
|
||||
|
||||
use super::{call_session_tool, CallRefused, Ctx, SessionAccess, Surface, ToolOutcome};
|
||||
use crate::db::ApiAuthed;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct BaseInternalUrl(String);
|
||||
|
||||
pub(crate) fn workspaced_service(base_internal_url: String) -> Router {
|
||||
Router::new()
|
||||
.route("/{name}", post(call_tool))
|
||||
.layer(Extension(BaseInternalUrl(base_internal_url)))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ToolCall {
|
||||
#[serde(default)]
|
||||
args: Value,
|
||||
#[serde(default)]
|
||||
context: ChatContext,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct ToolResponse {
|
||||
#[serde(flatten)]
|
||||
outcome: ToolOutcome,
|
||||
effects: Vec<Effect>,
|
||||
}
|
||||
|
||||
async fn call_tool(
|
||||
authed: ApiAuthed,
|
||||
Extension(BaseInternalUrl(base_internal_url)): Extension<BaseInternalUrl>,
|
||||
Path((w_id, name)): Path<(String, String)>,
|
||||
Json(call): Json<ToolCall>,
|
||||
) -> JsonResult<ToolResponse> {
|
||||
// A tool calls the API with a JWT carrying its caller's full rights, so a token
|
||||
// minted for something narrower (a job, a scope) must not reach it.
|
||||
if authed.job_id.is_some() || !is_effectively_unscoped(authed.scopes.as_deref()) {
|
||||
return Err(Error::PermissionDenied(
|
||||
"The AI session tools are only reachable with an unscoped user token".to_string(),
|
||||
));
|
||||
}
|
||||
let mut ctx = Ctx::new(&authed, &w_id, &base_internal_url, SessionAccess::Full);
|
||||
ctx.surface = Surface::Chat;
|
||||
ctx.chat = Some(&call.context);
|
||||
let outcome =
|
||||
call_session_tool(&ctx, &name, call.args)
|
||||
.await
|
||||
.map_err(|refused| match refused {
|
||||
CallRefused::UnknownTool(message)
|
||||
| CallRefused::NotAllowed(message)
|
||||
| CallRefused::NotAvailable(message) => Error::BadRequest(message),
|
||||
})?;
|
||||
let effects = ctx.effects.into_inner().unwrap();
|
||||
Ok(Json(ToolResponse { outcome, effects }))
|
||||
}
|
||||
|
||||
/// Browser-held state a tool needs and the server cannot see.
|
||||
#[derive(Deserialize, Default)]
|
||||
pub(crate) struct ChatContext {
|
||||
/// The editor open on each draft kind, at most one per kind.
|
||||
#[serde(default)]
|
||||
pub live_editors: Vec<LiveEditor>,
|
||||
/// The draft cells the browser holds: an open editor's, and any whose latest edit is
|
||||
/// not on the server yet. They are newer than the server's row.
|
||||
#[serde(default)]
|
||||
pub cells: Vec<Cell>,
|
||||
/// Run only the check that comes before the chat's confirmation card: what a
|
||||
/// confirmed call would refuse, and what it would change.
|
||||
#[serde(default)]
|
||||
pub check_only: bool,
|
||||
/// Whether the chat's user left the skill a call reads switched on.
|
||||
#[serde(default)]
|
||||
pub skill_enabled: Option<bool>,
|
||||
/// The folders the session works in, which a listing defaults to.
|
||||
#[serde(default)]
|
||||
pub scope_roots: Option<Vec<String>>,
|
||||
/// The call comes from an AI session, which has a preview panel and builds pipeline
|
||||
/// nodes in the folder's pipeline draft.
|
||||
#[serde(default)]
|
||||
pub session: bool,
|
||||
/// The workspace's AI provider resources and the models each serves, sent once a call
|
||||
/// asked for it with `needs_ai_provider_catalog`.
|
||||
#[serde(default)]
|
||||
pub ai_provider_catalog: Option<super::ai_providers::Catalog>,
|
||||
/// A run tool called in two phases around the chat's own argument form: `prepare`
|
||||
/// resolves what will run, `start` queues it with the arguments the form settled on.
|
||||
#[serde(default)]
|
||||
pub run: Option<RunPhase>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "phase", rename_all = "snake_case")]
|
||||
pub(crate) enum RunPhase {
|
||||
Prepare,
|
||||
Start {
|
||||
/// What `prepare` resolved, so the run is the version the form was shown for;
|
||||
/// absent for a tool with no form, which resolves and starts in one call.
|
||||
#[serde(default)]
|
||||
target: Option<super::runs::RunTarget>,
|
||||
#[serde(default)]
|
||||
args: Map<String, Value>,
|
||||
/// An agent step's form rows, each fed from the run's arguments.
|
||||
#[serde(default)]
|
||||
form_keys: Vec<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct LiveEditor {
|
||||
/// The draft kind (`script`, `flow`, `raw_app`, `trigger_schedule`, …).
|
||||
pub kind: String,
|
||||
/// The key the draft is stored under: `u/{user}/draft_{uuid}` for a new item.
|
||||
pub storage_path: String,
|
||||
/// The path the editor shows, which a rename leaves the storage key behind.
|
||||
pub effective_path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct Cell {
|
||||
pub kind: String,
|
||||
pub storage_path: String,
|
||||
pub value: Value,
|
||||
}
|
||||
|
||||
/// Something a call changed that the chat applies in the browser.
|
||||
#[derive(Serialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub(crate) enum Effect {
|
||||
/// Save `value` as the draft at `storage_path`, through the editor's own draft store.
|
||||
/// `last_sync` is the server row the value was built on, when it was read from the
|
||||
/// server rather than from a cell: the save detects a conflict against it.
|
||||
DraftWrite {
|
||||
kind: String,
|
||||
storage_path: String,
|
||||
value: Value,
|
||||
last_sync: Option<String>,
|
||||
force: bool,
|
||||
},
|
||||
/// Delete the draft at `storage_path`. `keep_live_editor` leaves an open editor's
|
||||
/// copy in place, detached from the server row.
|
||||
DraftDelete {
|
||||
kind: String,
|
||||
storage_path: String,
|
||||
last_sync: Option<String>,
|
||||
keep_live_editor: bool,
|
||||
},
|
||||
/// `get_run` read one job, which the card renders the run from.
|
||||
InspectedRun { job_id: String },
|
||||
/// What the call found that only its card shows, not the model.
|
||||
Facts(serde_json::Map<String, Value>),
|
||||
/// A patch to the tool's card, in the order the call reached it. One carrying
|
||||
/// `after_save` applies only once the chat saved the call's draft writes.
|
||||
Status(serde_json::Map<String, Value>),
|
||||
/// The call wrote nothing: it needs the AI provider catalog, which the chat builds, and
|
||||
/// is to be made again with it. `resource_refs` are the ones the flow references.
|
||||
NeedsAiProviderCatalog { resource_refs: Vec<String> },
|
||||
/// The code a write changed, for the card's diff: of a script in `language`, or of an
|
||||
/// app file at `file_path` (`before_file_path` when its language changed).
|
||||
CodeDiff {
|
||||
before: String,
|
||||
after: String,
|
||||
language: Option<String>,
|
||||
file_path: Option<String>,
|
||||
before_file_path: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
impl ChatContext {
|
||||
fn live_editor(&self, kind: &str) -> Option<&LiveEditor> {
|
||||
self.live_editors.iter().find(|e| e.kind == kind)
|
||||
}
|
||||
|
||||
/// The key a draft named `path` is stored under: an open editor's storage key when
|
||||
/// `path` is either of its names, else `path` itself.
|
||||
pub fn storage_path<'a>(&'a self, kind: &str, path: &'a str) -> &'a str {
|
||||
match self.live_editor(kind) {
|
||||
Some(editor)
|
||||
if path == editor.storage_path
|
||||
|| editor.effective_path.as_deref() == Some(path) =>
|
||||
{
|
||||
&editor.storage_path
|
||||
}
|
||||
_ => path,
|
||||
}
|
||||
}
|
||||
|
||||
/// The path a draft stored at `storage_path` is shown under, and whether an editor is
|
||||
/// open on it.
|
||||
pub fn display_path<'a>(&'a self, kind: &str, storage_path: &'a str) -> (&'a str, bool) {
|
||||
match self.live_editor(kind) {
|
||||
Some(editor) if editor.storage_path == storage_path => (
|
||||
editor
|
||||
.effective_path
|
||||
.as_deref()
|
||||
.filter(|p| !p.is_empty())
|
||||
.unwrap_or(storage_path),
|
||||
true,
|
||||
),
|
||||
_ => (storage_path, false),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cell(&self, kind: &str, storage_path: &str) -> Option<&Value> {
|
||||
self.cells
|
||||
.iter()
|
||||
.find(|c| c.kind == kind && c.storage_path == storage_path)
|
||||
.map(|c| &c.value)
|
||||
}
|
||||
}
|
||||
|
||||
impl super::Ctx<'_> {
|
||||
/// Patch the chat's card for this call.
|
||||
pub(super) fn status(&self, content: impl Into<String>) {
|
||||
let mut patch = serde_json::Map::new();
|
||||
patch.insert("content".into(), Value::String(content.into()));
|
||||
self.effect(Effect::Status(patch));
|
||||
}
|
||||
|
||||
/// The card's label while a draft write builds and saves.
|
||||
pub(super) fn saving_draft(&self, item_type: &str, path: &str) {
|
||||
self.status(format!("Saving {item_type} \"{path}\" as a draft…"));
|
||||
}
|
||||
|
||||
/// `status`, applied only once the chat saved the call's draft writes and deletes.
|
||||
pub(super) fn status_after_save(&self, content: impl Into<String>, result: Option<&str>) {
|
||||
let mut patch = serde_json::Map::new();
|
||||
patch.insert("content".into(), Value::String(content.into()));
|
||||
if let Some(result) = result {
|
||||
patch.insert("result".into(), Value::String(result.to_string()));
|
||||
}
|
||||
patch.insert("after_save".into(), Value::Bool(true));
|
||||
self.effect(Effect::Status(patch));
|
||||
}
|
||||
|
||||
pub(super) fn code_diff(&self, before: &str, after: &str, language: Option<&str>) {
|
||||
self.effect(Effect::CodeDiff {
|
||||
before: before.to_string(),
|
||||
after: after.to_string(),
|
||||
language: language.map(String::from),
|
||||
file_path: None,
|
||||
before_file_path: None,
|
||||
});
|
||||
}
|
||||
|
||||
/// `code_diff` of an app file, whose language its path gives.
|
||||
pub(super) fn file_diff(
|
||||
&self,
|
||||
before: &str,
|
||||
after: &str,
|
||||
file_path: &str,
|
||||
before_file_path: &str,
|
||||
) {
|
||||
self.effect(Effect::CodeDiff {
|
||||
before: before.to_string(),
|
||||
after: after.to_string(),
|
||||
language: None,
|
||||
file_path: Some(file_path.to_string()),
|
||||
before_file_path: (before_file_path != file_path).then(|| before_file_path.to_string()),
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether the call comes from an AI session rather than the side-panel chat.
|
||||
pub(super) fn in_session(&self) -> bool {
|
||||
self.chat.is_some_and(|chat| chat.session)
|
||||
}
|
||||
|
||||
/// Hand the card facts the model does not read.
|
||||
pub(super) fn facts(&self, facts: Value) {
|
||||
if let Value::Object(facts) = facts {
|
||||
self.effect(Effect::Facts(facts));
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the call is the chat's check before its confirmation card.
|
||||
pub(super) fn check_only(&self) -> bool {
|
||||
self.chat.is_some_and(|chat| chat.check_only)
|
||||
}
|
||||
|
||||
/// Mark the card failed with `message`, and answer it as the tool's result.
|
||||
pub(super) fn failed(&self, message: String) -> String {
|
||||
let mut patch = serde_json::Map::new();
|
||||
patch.insert("content".into(), Value::String(message.clone()));
|
||||
patch.insert("error".into(), Value::String(message.clone()));
|
||||
self.effect(Effect::Status(patch));
|
||||
message
|
||||
}
|
||||
|
||||
/// The key a draft named `path` is stored under; `path` itself outside the chat.
|
||||
pub(super) fn storage_path<'s>(&'s self, kind: &str, path: &'s str) -> &'s str {
|
||||
self.chat.map_or(path, |chat| chat.storage_path(kind, path))
|
||||
}
|
||||
|
||||
/// The path a draft stored at `storage_path` is shown under, and whether an editor is
|
||||
/// open on it.
|
||||
pub(super) fn display_path<'s>(&'s self, kind: &str, storage_path: &'s str) -> (&'s str, bool) {
|
||||
self.chat.map_or((storage_path, false), |chat| {
|
||||
chat.display_path(kind, storage_path)
|
||||
})
|
||||
}
|
||||
}
|
||||
+81
-39
@@ -5,7 +5,10 @@ use std::sync::LazyLock;
|
||||
use regex::Regex;
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use super::runs::{backgrounded_summary, run_script_preview, wait_budget, wait_job};
|
||||
use super::runs::{
|
||||
backgrounded_summary, run_script_preview, run_tool, start_run, wait_budget, wait_job, Resolved,
|
||||
RunTarget,
|
||||
};
|
||||
use super::workspace::{api_message, path_enc};
|
||||
use super::{array, enc, js_str, non_null, opt_str_arg, pretty, str_arg, truthy, Ctx, ToolResult};
|
||||
|
||||
@@ -128,6 +131,9 @@ async fn list_datatables(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
if truthy(d.get("error")) {
|
||||
out.insert("error".into(), d["error"].clone());
|
||||
}
|
||||
if truthy(d.get("migrations_enabled")) {
|
||||
out.insert("migrations_enabled".into(), Value::Bool(true));
|
||||
}
|
||||
if truthy(d.get("permissioned")) {
|
||||
for key in ["usable_roles", "default_role"] {
|
||||
if let Some(v) = d.get(key) {
|
||||
@@ -221,30 +227,33 @@ async fn exec_datatable_sql(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
let name = str_arg(args, "datatable_name")?;
|
||||
let sql = str_arg(args, "sql")?;
|
||||
let role = role_arg(args)?;
|
||||
let failed = |e: String| format!("Failed to execute test run: {e}");
|
||||
|
||||
let database = match role {
|
||||
None => format!("datatable://{name}"),
|
||||
// A stored name holding a `?` is read whole by the server, so a role cannot follow it.
|
||||
Some(role) if name.contains('?') => {
|
||||
return Err(failed(format!("Data table '{name}' has a '?' in its name, so it can only be used here as its default role. Rename it to connect as role '{role}'.")));
|
||||
}
|
||||
Some(role) => format!("datatable://{name}?role={role}"),
|
||||
let resolved = async {
|
||||
Ok(Resolved {
|
||||
target: RunTarget::DatatableSql {
|
||||
datatable: name.to_string(),
|
||||
sql: sql.to_string(),
|
||||
role: role.map(String::from),
|
||||
},
|
||||
schema: None,
|
||||
code: None,
|
||||
lang: None,
|
||||
summary: None,
|
||||
runnable_kind: "script",
|
||||
start_message: format!("Executing SQL on \"{name}\"..."),
|
||||
conversational: false,
|
||||
module: None,
|
||||
})
|
||||
};
|
||||
let id = run_script_preview(
|
||||
ctx,
|
||||
None,
|
||||
"postgresql",
|
||||
sql,
|
||||
json!({ "database": database }),
|
||||
)
|
||||
run_tool(ctx, args, resolved, async |resolved: Resolved| {
|
||||
let id = start_run(ctx, &resolved.target, Map::new(), &[])
|
||||
.await
|
||||
.map_err(|e| format!("Failed to execute test run: {e}"))?;
|
||||
match wait_job(ctx, &id, wait_budget(args), false).await {
|
||||
Some(job) => Ok(format_datatable_sql_completion(&job, name)),
|
||||
None => Ok(backgrounded_summary(&id, &format!("SQL · {name}"))),
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(failed)?;
|
||||
|
||||
match wait_job(ctx, &id, wait_budget(args), false).await {
|
||||
Some(job) => Ok(format_datatable_sql_completion(&job, name)),
|
||||
None => Ok(backgrounded_summary(&id, &format!("SQL · {name}"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn format_datatable_sql_completion(job: &Value, datatable_name: &str) -> String {
|
||||
@@ -309,9 +318,13 @@ async fn migrations_status(ctx: &Ctx<'_>, datatable_name: &str) -> Result<Value,
|
||||
}
|
||||
|
||||
/// `POST` without a body: applying and rolling back take their target from the query.
|
||||
/// The migration routes run each migration as a job and wait for it, `TIMEOUT_WAIT_RESULT`
|
||||
/// (600 s by default) apiece, so a run of several outlasts any per-request budget.
|
||||
const MIGRATION_RUN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3600);
|
||||
|
||||
async fn post_migrations(ctx: &Ctx<'_>, path: &str) -> Result<Value, String> {
|
||||
let text = ctx
|
||||
.request("POST", path, None)
|
||||
.request_within("POST", path, None, MIGRATION_RUN_TIMEOUT)
|
||||
.await
|
||||
.map_err(|e| api_message(&e).to_string())?;
|
||||
serde_json::from_str(&text).map_err(|e| format!("unexpected response: {e}"))
|
||||
@@ -449,9 +462,12 @@ async fn list_datatable_migrations(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
let version = version_arg(args)?;
|
||||
let status = match migrations_status(ctx, datatable_name).await {
|
||||
Ok(status) => status,
|
||||
Err(e) => return Ok(format!("Error listing migrations: {e}")),
|
||||
Err(e) => return Ok(ctx.failed(format!("Error listing migrations: {}", api_message(&e)))),
|
||||
};
|
||||
if !truthy(status.get("enabled")) {
|
||||
ctx.status(format!(
|
||||
"Migrations are not enabled on \"{datatable_name}\""
|
||||
));
|
||||
return Ok(format!("Migrations are not enabled on datatable \"{datatable_name}\": its schema is changed with plain SQL and there is no history to list. Enabling them is a workspace admin's decision, made in Workspace settings → Data Tables."));
|
||||
}
|
||||
let migrations = array(status.get("migrations"));
|
||||
@@ -474,16 +490,24 @@ async fn list_datatable_migrations(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
if truthy(status.get("error")) {
|
||||
out.insert("error".into(), status["error"].clone());
|
||||
}
|
||||
ctx.status(format!(
|
||||
"Listed {} migration(s) of \"{datatable_name}\"",
|
||||
migrations.len()
|
||||
));
|
||||
return Ok(pretty(&Value::Object(out)));
|
||||
};
|
||||
let Some(migration) = migrations
|
||||
.iter()
|
||||
.find(|m| m["timestamp"].as_i64() == Some(version))
|
||||
else {
|
||||
return Ok(format!(
|
||||
return Ok(ctx.failed(format!(
|
||||
"No migration {version} on datatable \"{datatable_name}\""
|
||||
));
|
||||
)));
|
||||
};
|
||||
ctx.status(format!(
|
||||
"Read migration {}",
|
||||
migration_label(&version.into(), &migration["name"])
|
||||
));
|
||||
let mut out = Map::new();
|
||||
out.insert("version".into(), version.into());
|
||||
out.insert("name".into(), migration["name"].clone());
|
||||
@@ -605,11 +629,12 @@ async fn create_datatable_migration(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
}
|
||||
let version = match save_migration(ctx, datatable_name, version, definition).await {
|
||||
Ok(Ok(version)) => version,
|
||||
Ok(Err(message)) => return Ok(message),
|
||||
Err(e) => return Ok(format!("Error saving migration: {}", api_message(&e))),
|
||||
Ok(Err(message)) => return Ok(ctx.failed(message)),
|
||||
Err(e) => return Ok(ctx.failed(format!("Error saving migration: {}", api_message(&e)))),
|
||||
};
|
||||
let label = format!("{version} ({name})");
|
||||
if args.get("apply") == Some(&Value::Bool(false)) {
|
||||
ctx.status(format!("Saved migration {label} as pending"));
|
||||
return Ok(format!(
|
||||
"Saved migration {label} as pending. It is not applied yet."
|
||||
));
|
||||
@@ -619,19 +644,27 @@ async fn create_datatable_migration(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
let own_scope = (!scope.is_empty()).then_some(scope.as_slice());
|
||||
let earlier = match earlier_pending(ctx, datatable_name, version, own_scope).await {
|
||||
Ok(earlier) => earlier,
|
||||
Err(e) => return Ok(format!("Saved migration {label} as pending, but could not check what else is pending, so it was not applied: {e}")),
|
||||
Err(e) => return Ok(ctx.failed(format!("Saved migration {label} as pending, but could not check what else is pending, so it was not applied: {}", api_message(&e)))),
|
||||
};
|
||||
if !earlier.is_empty() {
|
||||
ctx.status(format!(
|
||||
"Saved migration {label}; {} earlier migration(s) still pending",
|
||||
earlier.len()
|
||||
));
|
||||
return Ok(format!("Saved migration {label} as pending without applying it: earlier migrations are not applied yet ({}) and it may depend on them. Tell the user, then apply them all in order with run_datatable_migrations.", earlier.join(", ")));
|
||||
}
|
||||
|
||||
ctx.status(format!("Applying migration {label}..."));
|
||||
let run = format!(
|
||||
"{}?only={version}",
|
||||
migrations_path(ctx, "run_datatable_migrations", datatable_name)
|
||||
);
|
||||
Ok(match post_migrations(ctx, &run).await {
|
||||
Ok(_) => format!("Applied migration {label} on datatable \"{datatable_name}\"."),
|
||||
Err(e) => format!("Migration {label} is saved but failed to apply: {e}. It stays pending and blocks later migrations. If nothing of it was applied, fix it by calling this tool again with version {version}; otherwise, or to drop it, tell the user, who can edit or delete it in Workspace settings → Data Tables."),
|
||||
Ok(_) => {
|
||||
ctx.status(format!("Applied migration {label}"));
|
||||
format!("Applied migration {label} on datatable \"{datatable_name}\".")
|
||||
}
|
||||
Err(e) => ctx.failed(format!("Migration {label} is saved but failed to apply: {}. It stays pending and blocks later migrations. If nothing of it was applied, fix it by calling this tool again with version {version}; otherwise, or to drop it, tell the user, who can edit or delete it in Workspace settings → Data Tables.", api_message(&e))),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -642,8 +675,13 @@ async fn run_datatable_migrations(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
Ok(result) => {
|
||||
let applied = array(result.get("applied"));
|
||||
if applied.is_empty() {
|
||||
ctx.status("No pending migration to apply");
|
||||
format!("No pending migration to apply on datatable \"{datatable_name}\".")
|
||||
} else {
|
||||
ctx.status(format!(
|
||||
"Applied {} migration(s) on \"{datatable_name}\"",
|
||||
applied.len()
|
||||
));
|
||||
format!(
|
||||
"Applied {} migration(s) on datatable \"{datatable_name}\": {}.",
|
||||
applied.len(),
|
||||
@@ -651,7 +689,7 @@ async fn run_datatable_migrations(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
)
|
||||
}
|
||||
}
|
||||
Err(e) => format!("Error applying migrations: {e}. Migrations before the failing one may have been applied: list them to see."),
|
||||
Err(e) => ctx.failed(format!("Error applying migrations: {}. Migrations before the failing one may have been applied: list them to see.", api_message(&e))),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -663,12 +701,16 @@ async fn rollback_datatable_migration(ctx: &Ctx<'_>, args: &Value) -> ToolResult
|
||||
migrations_path(ctx, "rollback_datatable_migrations", datatable_name)
|
||||
);
|
||||
Ok(match post_migrations(ctx, &path).await {
|
||||
Ok(result) if array(result.get("rolled_back")).is_empty() => format!("Migration {version} is not applied on datatable \"{datatable_name}\", so there is nothing to roll back."),
|
||||
Ok(result) => format!(
|
||||
"Rolled back migration {} on datatable \"{datatable_name}\". It is pending again.",
|
||||
labels(result.get("rolled_back"))
|
||||
),
|
||||
Err(e) => format!("Error rolling back: {e}"),
|
||||
Ok(result) if array(result.get("rolled_back")).is_empty() => {
|
||||
ctx.status(format!("Migration {version} is not applied"));
|
||||
format!("Migration {version} is not applied on datatable \"{datatable_name}\", so there is nothing to roll back.")
|
||||
}
|
||||
Ok(result) => {
|
||||
let label = labels(result.get("rolled_back"));
|
||||
ctx.status(format!("Rolled back migration {label}"));
|
||||
format!("Rolled back migration {label} on datatable \"{datatable_name}\". It is pending again.")
|
||||
}
|
||||
Err(e) => ctx.failed(format!("Error rolling back: {}", api_message(&e))),
|
||||
})
|
||||
}
|
||||
|
||||
+46
-17
@@ -14,7 +14,7 @@ use super::workspace::{
|
||||
};
|
||||
use super::{
|
||||
array, bool_arg, enc, is_not_found, js_str, matches_glob, non_null, opt_str_arg, pretty,
|
||||
str_arg, truthy, Ctx, ToolResult,
|
||||
str_arg, truthy, Ctx, Surface, ToolResult,
|
||||
};
|
||||
|
||||
pub(super) const TOOLS: &[&str] = &["deploy_workspace_item", "delete_workspace_item", "diff"];
|
||||
@@ -299,7 +299,7 @@ async fn undeployed_runnable_targets(ctx: &Ctx<'_>, runnables: &Map<String, Valu
|
||||
} else {
|
||||
kind
|
||||
};
|
||||
let (Some(target_type @ ("script" | "flow")), Some(path)) = (
|
||||
let (Some(target_type @ ("script" | "flow" | "agent")), Some(path)) = (
|
||||
target_type,
|
||||
runnable
|
||||
.get("path")
|
||||
@@ -309,13 +309,30 @@ async fn undeployed_runnable_targets(ctx: &Ctx<'_>, runnables: &Map<String, Valu
|
||||
continue;
|
||||
};
|
||||
// Advisory: a failed probe must not block the deploy it annotates.
|
||||
if let Ok(false) = deployed_item_exists(ctx, target_type, None, path).await {
|
||||
let deployed = if target_type == "agent" {
|
||||
agent_exists(ctx, path).await
|
||||
} else {
|
||||
deployed_item_exists(ctx, target_type, None, path).await
|
||||
};
|
||||
if let Ok(false) = deployed {
|
||||
targets.push(format!("\"{key}\" → {target_type} \"{path}\""));
|
||||
}
|
||||
}
|
||||
targets
|
||||
}
|
||||
|
||||
/// Whether a saved agent, an `ai_agent` resource, is at `path`: another resource runs nothing.
|
||||
async fn agent_exists(ctx: &Ctx<'_>, path: &str) -> Result<bool, String> {
|
||||
match ctx
|
||||
.get(&ctx.ws(&format!("resources/get/{}", path_enc(path))))
|
||||
.await
|
||||
{
|
||||
Ok(resource) => Ok(resource["resource_type"] == "ai_agent"),
|
||||
Err(e) if is_not_found(&e) => Ok(false),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
async fn guest_access_is_live(ctx: &Ctx<'_>) -> bool {
|
||||
let Ok(usage) = ctx.get(&ctx.ws("workspaces/guest_usage")).await else {
|
||||
return false;
|
||||
@@ -574,7 +591,7 @@ async fn deploy_item(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
}
|
||||
|
||||
// The baseline keeps a draft saved since the read above from being deleted undeployed.
|
||||
delete_draft(ctx, &kind, path, draft.created_at.as_deref()).await?;
|
||||
delete_draft(ctx, &kind, path, draft.created_at.as_deref(), true).await?;
|
||||
|
||||
let note = note.map(|note| format!(" {note}")).unwrap_or_default();
|
||||
Ok(mutation_result(
|
||||
@@ -582,7 +599,7 @@ async fn deploy_item(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
item_type,
|
||||
path,
|
||||
trigger_kind,
|
||||
deployed_page(item_type, path, value).map(|page| ctx.page_url(&page)),
|
||||
deployed_page(item_type, path, value).and_then(|page| ctx.link(&page)),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -597,17 +614,28 @@ async fn delete_item(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
if item_type == "trigger" && trigger_kind.is_none() {
|
||||
return Err("trigger_kind is required when deleting a trigger.".to_string());
|
||||
}
|
||||
// Undoing a draft is a discard, not a delete: say so before the delete route 404s.
|
||||
if !deployed_item_exists(ctx, item_type, trigger_kind, path).await? {
|
||||
let draft = get_draft_item(ctx, item_type, path, trigger_kind).await?;
|
||||
return Err(if draft.is_some() {
|
||||
format!(
|
||||
"No deployed {item_type} at \"{path}\" — it only exists as a draft, so there is nothing to delete \
|
||||
from the workspace. Call discard_local_draft with the same arguments to remove the draft."
|
||||
)
|
||||
} else {
|
||||
format!("No {item_type} at \"{path}\": neither a deployed item nor a draft. Nothing to delete.")
|
||||
});
|
||||
// Undoing a draft is a discard, not a delete: say so before the delete route 404s. The
|
||||
// chat asks this before its confirmation card, which a refused delete never shows.
|
||||
if ctx.surface == Surface::Mcp || ctx.check_only() {
|
||||
if !deployed_item_exists(ctx, item_type, trigger_kind, path).await? {
|
||||
let draft = get_draft_item(ctx, item_type, path, trigger_kind).await?;
|
||||
let refusal = if draft.is_some() {
|
||||
format!(
|
||||
"No deployed {item_type} at \"{path}\" — it only exists as a draft, so there is nothing to delete \
|
||||
from the workspace. Call discard_local_draft with the same arguments to remove the draft."
|
||||
)
|
||||
} else {
|
||||
format!("No {item_type} at \"{path}\": neither a deployed item nor a draft. Nothing to delete.")
|
||||
};
|
||||
if ctx.check_only() {
|
||||
ctx.facts(json!({ "refused": refusal }));
|
||||
return Ok(refusal);
|
||||
}
|
||||
return Err(refusal);
|
||||
}
|
||||
if ctx.check_only() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
}
|
||||
|
||||
let path_in_url = path_enc(path);
|
||||
@@ -626,8 +654,9 @@ async fn delete_item(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
.await?;
|
||||
}
|
||||
if let Some(kind) = draft_kind(item_type, trigger_kind) {
|
||||
delete_draft(ctx, &kind, path, None).await?;
|
||||
delete_draft(ctx, &kind, path, None, false).await?;
|
||||
}
|
||||
ctx.status_after_save(format!("Deleted {item_type} \"{path}\""), Some("Deleted"));
|
||||
Ok(mutation_result(
|
||||
format!(
|
||||
"Deleted {item_type} \"{path}\" from the workspace. Any matching draft was also cleared."
|
||||
+79
-70
@@ -9,6 +9,7 @@ use std::collections::{HashMap, HashSet};
|
||||
use serde_json::{json, Map, Value};
|
||||
use windmill_types::flows::FlowModule;
|
||||
|
||||
use super::ai_providers::{self, CatalogFor};
|
||||
use super::workspace::{
|
||||
compact_flow, empty_schema, find_and_replace, finish_draft_write, load_flow, persist_draft,
|
||||
write_base, Persist, FLOW_VALUE_SETTINGS_KEYS,
|
||||
@@ -69,7 +70,6 @@ const RESERVED_TOOL_NAMES: &[&str] = &[
|
||||
"Trigger",
|
||||
"__wm_web_search",
|
||||
];
|
||||
const PROVIDER_SHAPE: &str = r#"{ "type": "static", "value": { "kind": "<provider kind>", "resource": "$res:<resource path>", "model": "<model id>" } }"#;
|
||||
|
||||
fn module_id(module: &Value) -> &str {
|
||||
module.get("id").and_then(Value::as_str).unwrap_or_default()
|
||||
@@ -410,45 +410,6 @@ fn tool_name_error(name: &str, siblings: &[&str]) -> Option<String> {
|
||||
(siblings.iter().filter(|n| **n == name).count() > 1).then(|| "Duplicate tool name".into())
|
||||
}
|
||||
|
||||
/// A provider config that cannot run whatever the workspace holds.
|
||||
fn provider_shape_error(provider: Option<&Value>, step_type: &str) -> Option<String> {
|
||||
let provider = match provider {
|
||||
Some(Value::String(reference)) => {
|
||||
return Some(format!(
|
||||
"provider must be an object {PROVIDER_SHAPE}, not the resource reference string {}",
|
||||
json!(reference)
|
||||
))
|
||||
}
|
||||
Some(Value::Object(provider)) => provider,
|
||||
_ => return Some(format!("provider must be an object {PROVIDER_SHAPE}")),
|
||||
};
|
||||
let text = |key: &str| {
|
||||
provider
|
||||
.get(key)
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let kind = text("kind");
|
||||
if kind.is_empty() {
|
||||
return Some(format!(
|
||||
"provider.kind is missing. Expected {PROVIDER_SHAPE}"
|
||||
));
|
||||
}
|
||||
let decision_only = ["typesafe", "cloudflare"].contains(&kind);
|
||||
if step_type == "aidecision" && !decision_only && kind != "openai" {
|
||||
return Some(format!("an AI decision step runs on a decision model: provider.kind must be \"typesafe\", \"cloudflare\" or \"openai\", not \"{kind}\""));
|
||||
}
|
||||
if step_type != "aidecision" && decision_only {
|
||||
return Some(format!("\"{kind}\" serves decision models, which answer typed questions rather than messages: use an \"aidecision\" step rather than an AI agent"));
|
||||
}
|
||||
if !text("resource").starts_with("$res:") {
|
||||
return Some(format!("provider.resource must be a \"$res:<resource path>\" reference. Expected {PROVIDER_SHAPE}"));
|
||||
}
|
||||
text("model")
|
||||
.is_empty()
|
||||
.then(|| format!("provider.model is missing. Expected {PROVIDER_SHAPE}"))
|
||||
}
|
||||
|
||||
fn quoted_list(ids: &[String]) -> String {
|
||||
ids.iter()
|
||||
.map(|id| format!("\"{id}\""))
|
||||
@@ -465,7 +426,6 @@ fn validate_modules(modules: &mut Value) -> Result<HashSet<String>, String> {
|
||||
let mut ids = Vec::new();
|
||||
let mut providerless = Vec::new();
|
||||
let mut tool_names = Vec::new();
|
||||
let mut providers = Vec::new();
|
||||
walk(Some(modules), false, &mut |module, in_tool| {
|
||||
let id = module_id(module);
|
||||
// A tool is not a flow module: the agent that owns it checks its shape.
|
||||
@@ -517,13 +477,6 @@ fn validate_modules(modules: &mut Value) -> Result<HashSet<String>, String> {
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let is_static = |p: &&Value| p.get("type").and_then(Value::as_str) == Some("static");
|
||||
if let Some(provider) = provider.filter(|_| !linked).filter(is_static) {
|
||||
if let Some(error) = provider_shape_error(provider.get("value"), kind) {
|
||||
providers.push(format!("Step \"{id}\": {error}"));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if !shape_errors.is_empty() {
|
||||
@@ -551,12 +504,6 @@ fn validate_modules(modules: &mut Value) -> Result<HashSet<String>, String> {
|
||||
tool_names.join("; ")
|
||||
));
|
||||
}
|
||||
if !providers.is_empty() {
|
||||
return Err(format!(
|
||||
"Invalid AI agent provider configuration:\n{}",
|
||||
providers.join("\n")
|
||||
));
|
||||
}
|
||||
Ok(unique)
|
||||
}
|
||||
|
||||
@@ -722,8 +669,12 @@ fn validate_notes(raw: Option<&Value>, module_ids: &HashSet<String>) -> Result<V
|
||||
|
||||
/// Checks a compact flow view (`modules, schema, preprocessor_module, failure_module,
|
||||
/// groups, notes` and the top-level settings) and returns it with every structural key
|
||||
/// present, `null` when unset.
|
||||
fn validate_editable(raw: Value) -> Result<Map<String, Value>, String> {
|
||||
/// present, `null` when unset. Provider findings that do not block go to `warnings`.
|
||||
fn validate_editable(
|
||||
raw: Value,
|
||||
catalog: Option<&ai_providers::Catalog>,
|
||||
warnings: &mut Vec<String>,
|
||||
) -> Result<Map<String, Value>, String> {
|
||||
let Value::Object(mut flow) = raw else {
|
||||
return Err("Flow JSON must be an object".into());
|
||||
};
|
||||
@@ -744,8 +695,9 @@ fn validate_editable(raw: Value) -> Result<Map<String, Value>, String> {
|
||||
}
|
||||
validate_settings(&flow)?;
|
||||
|
||||
let mut modules = flow.remove("modules").unwrap_or(Value::Null);
|
||||
let mut modules = flow.shift_remove("modules").unwrap_or(Value::Null);
|
||||
let module_ids = validate_modules(&mut modules)?;
|
||||
ai_providers::validate(&modules, catalog, warnings)?;
|
||||
let schema = match flow.get("schema") {
|
||||
None | Some(Value::Null) => Value::Null,
|
||||
Some(schema @ Value::Object(_)) => schema.clone(),
|
||||
@@ -776,12 +728,12 @@ fn validate_editable(raw: Value) -> Result<Map<String, Value>, String> {
|
||||
editable.insert("modules".into(), modules);
|
||||
editable.insert("schema".into(), schema);
|
||||
for (key, _) in SPECIAL_MODULES {
|
||||
editable.insert(key.into(), flow.remove(key).unwrap_or(Value::Null));
|
||||
editable.insert(key.into(), flow.shift_remove(key).unwrap_or(Value::Null));
|
||||
}
|
||||
editable.insert("groups".into(), groups);
|
||||
editable.insert("notes".into(), notes);
|
||||
for key in FLOW_VALUE_SETTINGS_KEYS {
|
||||
if let Some(setting) = flow.remove(*key) {
|
||||
if let Some(setting) = flow.shift_remove(*key) {
|
||||
editable.insert((*key).into(), setting);
|
||||
}
|
||||
}
|
||||
@@ -804,6 +756,7 @@ struct FlowWrite<'a> {
|
||||
|
||||
async fn write_flow_draft(ctx: &Ctx<'_>, write: FlowWrite<'_>) -> ToolResult {
|
||||
let FlowWrite { path, mut value, .. } = write;
|
||||
ctx.saving_draft("flow", path);
|
||||
let base = write_base(ctx, "flow", path, None).await?;
|
||||
let existed = base.base.is_some();
|
||||
if let Some(groups) = write.groups {
|
||||
@@ -910,7 +863,13 @@ async fn write_flow(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
for key in STRUCTURAL_KEYS {
|
||||
raw.insert((*key).into(), json_arg(args, key)?);
|
||||
}
|
||||
let mut editable = validate_editable(Value::Object(raw))?;
|
||||
let catalog = match ai_providers::catalog_for(ctx, &raw["modules"]).await {
|
||||
CatalogFor::Requested => return Ok(String::new()),
|
||||
CatalogFor::Ready(catalog) => Some(catalog),
|
||||
CatalogFor::NotNeeded => None,
|
||||
};
|
||||
let mut warnings = Vec::new();
|
||||
let mut editable = validate_editable(Value::Object(raw), catalog.as_ref(), &mut warnings)?;
|
||||
|
||||
// A placeholder keeps the body the current flow has for that module, so a rewrite
|
||||
// does not have to send code it is not changing.
|
||||
@@ -924,9 +883,9 @@ async fn write_flow(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
|
||||
let schema = non_null(editable.get("schema")).cloned();
|
||||
let groups = non_null(editable.get("groups")).cloned();
|
||||
editable.remove("schema");
|
||||
editable.shift_remove("schema");
|
||||
editable.retain(|_, field| !field.is_null());
|
||||
write_flow_draft(
|
||||
let written = write_flow_draft(
|
||||
ctx,
|
||||
FlowWrite {
|
||||
path,
|
||||
@@ -940,7 +899,18 @@ async fn write_flow(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
force: args.get("override").and_then(Value::as_bool) == Some(true),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.await?;
|
||||
Ok(with_provider_warnings(ctx, written, &warnings))
|
||||
}
|
||||
|
||||
/// The provider findings that did not block the write, after the result. The chat appends
|
||||
/// them itself when its own save fails and replaces this text.
|
||||
fn with_provider_warnings(ctx: &Ctx<'_>, written: String, warnings: &[String]) -> String {
|
||||
let suffix = ai_providers::format_warnings(warnings);
|
||||
if !suffix.is_empty() {
|
||||
ctx.facts(json!({ "text_suffix": suffix }));
|
||||
}
|
||||
format!("{written}{suffix}")
|
||||
}
|
||||
|
||||
async fn patch_flow_json(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
@@ -959,10 +929,16 @@ async fn patch_flow_json(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
)?;
|
||||
let parsed: Value = serde_json::from_str(&updated)
|
||||
.map_err(|e| format!("Invalid JSON after replacement: {e}"))?;
|
||||
let editable = validate_editable(parsed)?;
|
||||
let catalog = match ai_providers::catalog_for(ctx, &parsed["modules"]).await {
|
||||
CatalogFor::Requested => return Ok(String::new()),
|
||||
CatalogFor::Ready(catalog) => Some(catalog),
|
||||
CatalogFor::NotNeeded => None,
|
||||
};
|
||||
let mut warnings = Vec::new();
|
||||
let editable = validate_editable(parsed, catalog.as_ref(), &mut warnings)?;
|
||||
let mut value = apply_editable(base.flow.get("value"), &editable, &scripts);
|
||||
finalize_inline_scripts(&mut value)?;
|
||||
write_flow_draft(
|
||||
let written = write_flow_draft(
|
||||
ctx,
|
||||
FlowWrite {
|
||||
path,
|
||||
@@ -976,14 +952,38 @@ async fn patch_flow_json(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
force: false,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.await?;
|
||||
Ok(with_provider_warnings(ctx, written, &warnings))
|
||||
}
|
||||
|
||||
/// A step as the chat's card names it: its id, and its summary when it has one.
|
||||
fn step_name(flow: Option<&Value>, module_id: &str) -> String {
|
||||
let mut flow = flow.and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
let mut summary = None;
|
||||
walk_flow(&mut flow, &mut |module, _| {
|
||||
if summary.is_none() && self::module_id(module) == module_id {
|
||||
summary = module
|
||||
.get("summary")
|
||||
.and_then(Value::as_str)
|
||||
.map(String::from);
|
||||
}
|
||||
});
|
||||
match summary.filter(|s| !s.is_empty()) {
|
||||
Some(summary) => format!("{module_id} \"{summary}\""),
|
||||
None => module_id.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_flow_module_code(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
let (path, module_id) = (str_arg(args, "path")?, str_arg(args, "module_id")?);
|
||||
let base = load_flow(ctx, path).await?;
|
||||
let (_, mut scripts) = compact_flow(base.flow.get("value").unwrap_or(&Value::Null), None);
|
||||
scripts.remove(module_id).ok_or_else(|| format!("Module \"{module_id}\" is not an inline rawscript in flow \"{path}\". (Path runnables, branches, and loops have no inline script content; use patch_flow_json to inspect them.)"))
|
||||
let code = scripts.remove(module_id).ok_or_else(|| format!("Module \"{module_id}\" is not an inline rawscript in flow \"{path}\". (Path runnables, branches, and loops have no inline script content; use patch_flow_json to inspect them.)"))?;
|
||||
ctx.status(format!(
|
||||
"Read code of step {}",
|
||||
step_name(base.flow.get("value"), module_id)
|
||||
));
|
||||
Ok(code)
|
||||
}
|
||||
|
||||
async fn set_flow_module_code(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
@@ -999,6 +999,14 @@ async fn set_flow_module_code(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
}
|
||||
scripts.insert(module_id.to_string(), code.to_string());
|
||||
let editable = compact.as_object().cloned().unwrap_or_default();
|
||||
// Several code edits of one flow read as identical rows under the generic flow label.
|
||||
ctx.status_after_save(
|
||||
format!(
|
||||
"Updated code of step {}",
|
||||
step_name(base.flow.get("value"), module_id)
|
||||
),
|
||||
None,
|
||||
);
|
||||
write_flow_draft(
|
||||
ctx,
|
||||
FlowWrite {
|
||||
@@ -1111,7 +1119,8 @@ mod tests {
|
||||
.to_string()
|
||||
.replace(",\"same_worker\":true", "")
|
||||
.replace("\"id\":\"b\"", "\"id\":\"c\"");
|
||||
let editable = validate_editable(serde_json::from_str(&patched).unwrap()).unwrap();
|
||||
let editable =
|
||||
validate_editable(serde_json::from_str(&patched).unwrap(), None, &mut vec![]).unwrap();
|
||||
let mut applied = apply_editable(Some(&value), &editable, &scripts);
|
||||
finalize_inline_scripts(&mut applied).unwrap();
|
||||
assert_eq!(content(&applied, "/0"), "A");
|
||||
@@ -1124,7 +1133,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn validation_reports_what_the_editor_would_refuse() {
|
||||
let check = |flow: Value| validate_editable(flow).unwrap_err();
|
||||
let check = |flow: Value| validate_editable(flow, None, &mut vec![]).unwrap_err();
|
||||
assert_eq!(
|
||||
check(json!({ "modules": [raw("a", ""), raw("a", "")] })),
|
||||
"Duplicate module IDs found in flow"
|
||||
@@ -1159,7 +1168,7 @@ mod tests {
|
||||
assert!(check(agent(json!([tool("search docs")]))).starts_with(
|
||||
"Invalid AI agent tool name(s): agent \"agent\" tool \"t\" is named \"search docs\" - Tool name must only contain letters, numbers and underscores. "
|
||||
));
|
||||
validate_editable(agent(json!([tool("search_docs")]))).unwrap();
|
||||
validate_editable(agent(json!([tool("search_docs")])), None, &mut vec![]).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
+20
File diff suppressed because one or more lines are too long
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"ai": "AI",
|
||||
"ai21": "AI21",
|
||||
"amqp": "AMQP",
|
||||
"api": "API",
|
||||
"aws": "AWS",
|
||||
"cms": "CMS",
|
||||
"crm": "CRM",
|
||||
"db": "DB",
|
||||
"ftp": "FTP",
|
||||
"gcp": "GCP",
|
||||
"gpg": "GPG",
|
||||
"hr": "HR",
|
||||
"http": "HTTP",
|
||||
"id": "ID",
|
||||
"ifs": "IFS",
|
||||
"json": "JSON",
|
||||
"jwt": "JWT",
|
||||
"ldap": "LDAP",
|
||||
"mcp": "MCP",
|
||||
"mqtt": "MQTT",
|
||||
"ms": "Microsoft",
|
||||
"nats": "NATS",
|
||||
"oauth": "OAuth",
|
||||
"odk": "ODK",
|
||||
"oidc": "OIDC",
|
||||
"rss": "RSS",
|
||||
"s3": "S3",
|
||||
"sdk": "SDK",
|
||||
"smtp": "SMTP",
|
||||
"sql": "SQL",
|
||||
"ssh": "SSH",
|
||||
"url": "URL",
|
||||
"ynab": "YNAB",
|
||||
"abstractapi": "AbstractAPI",
|
||||
"arcgis": "ArcGIS",
|
||||
"assemblyai": "AssemblyAI",
|
||||
"bigquery": "BigQuery",
|
||||
"chromadb": "ChromaDB",
|
||||
"circleci": "CircleCI",
|
||||
"clickhouse": "ClickHouse",
|
||||
"clickup": "ClickUp",
|
||||
"cockroachdb": "CockroachDB",
|
||||
"comapeo": "CoMapeo",
|
||||
"convertkit": "ConvertKit",
|
||||
"currencyapi": "CurrencyAPI",
|
||||
"customai": "CustomAI",
|
||||
"datocms": "DatoCMS",
|
||||
"dbt": "dbt",
|
||||
"deepl": "DeepL",
|
||||
"deepseek": "DeepSeek",
|
||||
"digitalocean": "DigitalOcean",
|
||||
"docspring": "DocSpring",
|
||||
"docusign": "DocuSign",
|
||||
"edgedb": "EdgeDB",
|
||||
"faunadb": "FaunaDB",
|
||||
"gcloud": "Google Cloud",
|
||||
"ghostcms": "Ghost CMS",
|
||||
"gitbook": "GitBook",
|
||||
"github": "GitHub",
|
||||
"gitlab": "GitLab",
|
||||
"googleai": "GoogleAI",
|
||||
"graphql": "GraphQL",
|
||||
"groqai": "GroqAI",
|
||||
"hubspot": "HubSpot",
|
||||
"ipinfo": "IPinfo",
|
||||
"kobotoolbox": "KoboToolbox",
|
||||
"leonardoai": "LeonardoAI",
|
||||
"linkedin": "LinkedIn",
|
||||
"lumaai": "LumaAI",
|
||||
"mailerlite": "MailerLite",
|
||||
"mongodb": "MongoDB",
|
||||
"mysql": "MySQL",
|
||||
"netbox": "NetBox",
|
||||
"netsuite": "NetSuite",
|
||||
"newsapi": "NewsAPI",
|
||||
"neondb": "NeonDB",
|
||||
"nocodb": "NocoDB",
|
||||
"openai": "OpenAI",
|
||||
"openrouter": "OpenRouter",
|
||||
"oracledb": "OracleDB",
|
||||
"pagerduty": "PagerDuty",
|
||||
"pandadoc": "PandaDoc",
|
||||
"paypal": "PayPal",
|
||||
"planetscale": "PlanetScale",
|
||||
"postgresql": "PostgreSQL",
|
||||
"readme": "ReadMe",
|
||||
"rest": "REST",
|
||||
"quickbooks": "QuickBooks",
|
||||
"sendgrid": "SendGrid",
|
||||
"servicenow": "ServiceNow",
|
||||
"signoz": "SigNoz",
|
||||
"surrealdb": "SurrealDB",
|
||||
"togetherai": "TogetherAI",
|
||||
"webscrapingai": "WebScrapingAI",
|
||||
"weatherapi": "WeatherAPI",
|
||||
"whatsapp": "WhatsApp",
|
||||
"woocommerce": "WooCommerce"
|
||||
}
|
||||
+1
-1
File diff suppressed because one or more lines are too long
+23
-7
@@ -6,7 +6,8 @@ use std::sync::LazyLock;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{opt_str_arg, str_arg, Ctx, ToolResult};
|
||||
use super::workspace::api_message;
|
||||
use super::{opt_str_arg, str_arg, Ctx, Surface, ToolResult};
|
||||
|
||||
pub(super) const TOOLS: &[&str] = &["get_instructions", "read_skill"];
|
||||
|
||||
@@ -57,6 +58,8 @@ const TRUNCATED: &str = "… [truncated]";
|
||||
|
||||
pub(super) struct Skill {
|
||||
pub path: String,
|
||||
/// Listed in the MCP instructions; the chat builds its own prompt.
|
||||
#[cfg_attr(not(feature = "mcp"), allow(dead_code))]
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
@@ -103,11 +106,19 @@ async fn read_skill(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
// reads any resource holding a string `content`.
|
||||
let listed = match list_skills(ctx).await {
|
||||
Ok(skills) => skills.iter().any(|skill| skill.path == path),
|
||||
Err(e) => return Ok(read_failed(path, &e)),
|
||||
Err(e) => return Ok(read_failed(ctx, path, api_message(&e))),
|
||||
};
|
||||
if !listed {
|
||||
// The chat's user can switch a skill off for that chat, a setting their browser holds.
|
||||
let switched_off = ctx
|
||||
.chat
|
||||
.is_some_and(|chat| !chat.skill_enabled.unwrap_or(true));
|
||||
if !listed || switched_off {
|
||||
let (available, listing) = match ctx.surface {
|
||||
Surface::Chat => ("available to this chat", "the system prompt"),
|
||||
Surface::Mcp => ("available here", "the instructions"),
|
||||
};
|
||||
return Ok(format!(
|
||||
"\"{path}\" is not one of the skills available here. Only the paths listed under \"Skills\" in the instructions can be read."
|
||||
"\"{path}\" is not one of the skills {available}. Only the paths listed under \"Skills\" in {listing} can be read."
|
||||
));
|
||||
}
|
||||
let value = match ctx
|
||||
@@ -115,10 +126,11 @@ async fn read_skill(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
.await
|
||||
{
|
||||
Ok(value) => value,
|
||||
Err(e) => return Ok(read_failed(path, &e)),
|
||||
Err(e) => return Ok(read_failed(ctx, path, api_message(&e))),
|
||||
};
|
||||
let Some(body) = value.get("content").and_then(Value::as_str) else {
|
||||
return Ok(read_failed(
|
||||
ctx,
|
||||
path,
|
||||
&format!("resource {path} has no string \"content\" — is it an {SKILL_RESOURCE_TYPE}?"),
|
||||
));
|
||||
@@ -135,8 +147,12 @@ async fn read_skill(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
Ok(format!("Skill: {path}\n\nInstructions:\n{body}"))
|
||||
}
|
||||
|
||||
fn read_failed(path: &str, message: &str) -> String {
|
||||
fn read_failed(ctx: &Ctx<'_>, path: &str, message: &str) -> String {
|
||||
let listing = match ctx.surface {
|
||||
Surface::Chat => "the system prompt",
|
||||
Surface::Mcp => "the instructions",
|
||||
};
|
||||
format!(
|
||||
"Failed to read skill \"{path}\": {message}. Check the path against the Skills list in the instructions."
|
||||
"Failed to read skill \"{path}\": {message}. Check the path against the Skills list in {listing}."
|
||||
)
|
||||
}
|
||||
+3
-3
@@ -121,7 +121,7 @@ async fn appendix(ctx: &Ctx<'_>) -> String {
|
||||
}
|
||||
|
||||
/// The whole prompt, for a connection that reaches one workspace.
|
||||
pub(in crate::mcp) async fn session_instructions(ctx: &Ctx<'_>) -> String {
|
||||
pub(crate) async fn session_instructions(ctx: &Ctx<'_>) -> String {
|
||||
let mut prompt = PARTS
|
||||
.base
|
||||
.replace("{{folder_guidance}}", &folder_guidance(ctx.auth))
|
||||
@@ -132,7 +132,7 @@ pub(in crate::mcp) async fn session_instructions(ctx: &Ctx<'_>) -> String {
|
||||
|
||||
/// The prompt without anything specific to a workspace, for a connection that reaches
|
||||
/// several: usernames are per workspace, so paths read `u/<username>/...`.
|
||||
pub(in crate::mcp) fn generic_session_instructions() -> String {
|
||||
pub(crate) fn generic_session_instructions() -> String {
|
||||
PARTS
|
||||
.base
|
||||
.replace("{{folder_guidance}}", "")
|
||||
@@ -140,7 +140,7 @@ pub(in crate::mcp) fn generic_session_instructions() -> String {
|
||||
}
|
||||
|
||||
/// What `generic_session_instructions` leaves out, for one workspace.
|
||||
pub(in crate::mcp) async fn workspace_context(ctx: &Ctx<'_>) -> String {
|
||||
pub(crate) async fn workspace_context(ctx: &Ctx<'_>) -> String {
|
||||
let username = ctx.auth.username();
|
||||
format!(
|
||||
"Workspace `{}`. Your username here is \"{username}\", so your personal paths are \
|
||||
+4
-3
@@ -44,7 +44,7 @@ static SCHEDULE_SCHEMA: LazyLock<Value> = LazyLock::new(|| {
|
||||
let mut schema = tool_schema("write_schedule");
|
||||
let advanced: Value = serde_json::from_str(&SCHEMAS.schedule).unwrap_or_default();
|
||||
if let Some(properties) = schema.get_mut("properties").and_then(Value::as_object_mut) {
|
||||
properties.remove("advanced");
|
||||
properties.shift_remove("advanced");
|
||||
if let Some(advanced) = advanced.get("properties").and_then(Value::as_object) {
|
||||
properties.extend(advanced.clone());
|
||||
}
|
||||
@@ -282,7 +282,7 @@ fn into_object(value: Option<Value>) -> Map<String, Value> {
|
||||
fn merge_config(base: Option<Value>, config: Value, path: &str) -> Map<String, Value> {
|
||||
let mut draft = into_object(base);
|
||||
for key in ["workspace_id", "edited_by", "edited_at", "email", "error"] {
|
||||
draft.remove(key);
|
||||
draft.shift_remove(key);
|
||||
}
|
||||
draft.extend(into_object(Some(config)));
|
||||
draft.insert("path".into(), json!(path));
|
||||
@@ -454,6 +454,7 @@ async fn write_draft(
|
||||
from_deployed: impl FnOnce(Value) -> Value,
|
||||
build: impl FnOnce(Option<Value>) -> Result<Value, String>,
|
||||
) -> ToolResult {
|
||||
ctx.saving_draft(item_type, path);
|
||||
let base = write_base(ctx, item_type, path, trigger_kind).await?;
|
||||
let existed = base.base.is_some();
|
||||
let from_draft = base.from_draft;
|
||||
@@ -480,7 +481,7 @@ async fn write_draft(
|
||||
fn take_override(parsed: &mut Value) -> bool {
|
||||
parsed
|
||||
.as_object_mut()
|
||||
.and_then(|o| o.remove("override"))
|
||||
.and_then(|o| o.shift_remove("override"))
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
+259
-64
@@ -1,13 +1,17 @@
|
||||
//! Lookups that touch no draft: hub, docs, npm, resource types, workers, folders.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use futures::future::join_all;
|
||||
use serde_json::{json, Map, Value};
|
||||
use windmill_common::utils::HTTP_CLIENT;
|
||||
|
||||
use super::chat::Effect;
|
||||
use super::workspace::api_message;
|
||||
use super::{
|
||||
array, enc, is_not_found, opt_str_arg, pretty, str_arg, truthy, Ctx, ToolResult, SCHEMAS,
|
||||
array, enc, is_not_found, js_head, js_len, opt_str_arg, pretty, str_arg, truthy, Ctx,
|
||||
ToolResult, SCHEMAS,
|
||||
};
|
||||
|
||||
pub(super) const TOOLS: &[&str] = &[
|
||||
@@ -28,7 +32,7 @@ pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult
|
||||
match name {
|
||||
"search_hub_scripts" => search_hub_scripts(ctx, args).await,
|
||||
"get_hub_integration" => get_hub_integration(ctx, args).await,
|
||||
"search_npm_packages" => search_npm_packages(args).await,
|
||||
"search_npm_packages" => search_npm_packages(ctx, args).await,
|
||||
"search_docs" => search_docs(ctx, args).await,
|
||||
"read_docs_page" => read_docs_page(ctx, args).await,
|
||||
"search_resource_types" => search_resource_types(ctx, args).await,
|
||||
@@ -90,12 +94,37 @@ async fn hub_integrations(ctx: &Ctx<'_>) -> Vec<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The frontend's `RESOURCE_TYPE_WORDS`: how a slug word reads where capitalizing gets it
|
||||
/// wrong, some into several words (`gcloud` -> `Google Cloud`).
|
||||
static DISPLAY_WORDS: LazyLock<HashMap<String, String>> = LazyLock::new(|| {
|
||||
serde_json::from_str(include_str!("gen/display_words.json"))
|
||||
.expect("gen/display_words.json is valid")
|
||||
});
|
||||
|
||||
/// What the frontend's `integrationDisplayName` calls a slug the hub names nothing.
|
||||
fn slug_display_name(slug: &str) -> String {
|
||||
slug.split(['_', '-'])
|
||||
.filter(|w| !w.is_empty())
|
||||
.map(|w| {
|
||||
DISPLAY_WORDS
|
||||
.get(&w.to_ascii_lowercase())
|
||||
.cloned()
|
||||
.unwrap_or_else(|| w.to_string())
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
/// A token matches a whole word of the slug or display name, or extends one from four
|
||||
/// characters on: a bare substring test makes `for` hit sales*for*ce.
|
||||
fn token_matches_integration(token: &str, integration: &Value) -> bool {
|
||||
let name = integration.get("name").and_then(Value::as_str);
|
||||
let display_name = integration.get("display_name").and_then(Value::as_str);
|
||||
let words: Vec<String> = [name, display_name]
|
||||
let display_name = integration
|
||||
.get("display_name")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)
|
||||
.or_else(|| name.map(slug_display_name));
|
||||
let words: Vec<String> = [name, display_name.as_deref()]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flat_map(words)
|
||||
@@ -254,8 +283,9 @@ async fn get_hub_integration(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
Ok(doc) => doc,
|
||||
Err(e) => {
|
||||
// Only a 404 means the integration is absent. Reporting a timeout the same
|
||||
// way would teach the model that a real integration does not exist.
|
||||
let error = if is_not_found(&e) {
|
||||
// way would teach the model that a real integration does not exist. No slug holds
|
||||
// a `/`, and the route refuses one as malformed rather than absent.
|
||||
let error = if is_not_found(&e) || integration.contains('/') {
|
||||
format!("No hub metadata for \"{integration}\".")
|
||||
} else {
|
||||
format!("Could not reach the hub for \"{integration}\"; it may still exist. Read its scripts instead, or try again.")
|
||||
@@ -347,49 +377,183 @@ async fn get_hub_integration(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
// npm
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const NPM_SCORE_THRESHOLD: f64 = 1000.0;
|
||||
/// The session caps a package's readme and types at 1% of its model's context window
|
||||
/// each. The caller's model is unknown here, so this is 1% of the window the session
|
||||
/// assumes for an unknown model (128000).
|
||||
/// The registry's best match is kept, and the runner-up only when it scores this share of it:
|
||||
/// the scores have no fixed scale (a descriptive query's right answer can score a few hundred,
|
||||
/// a package's own name thousands), so a match is judged against the best one.
|
||||
const NPM_RUNNER_UP_SHARE: f64 = 0.6;
|
||||
/// A package's readme and types are each capped at 1% of the model's context window. An MCP
|
||||
/// client's model is unknown, so this is 1% of the window assumed for an unknown model (128000).
|
||||
const NPM_TEXT_LIMIT: usize = 1280;
|
||||
|
||||
fn take_chars(text: &str, limit: usize) -> String {
|
||||
text.chars().take(limit).collect()
|
||||
}
|
||||
|
||||
async fn fetch(url: &str) -> Result<reqwest::Response, reqwest::Error> {
|
||||
HTTP_CLIENT.get(url).send().await
|
||||
}
|
||||
|
||||
/// The package's declared entry declaration file. The session walks every `.d.ts` of the
|
||||
/// package in the browser and keeps the same number of characters of the result.
|
||||
async fn npm_package_types(name: &str, version: &str) -> Option<String> {
|
||||
let base = format!("https://unpkg.com/{name}@{version}");
|
||||
let manifest: Value = fetch(&format!("{base}/package.json"))
|
||||
.await
|
||||
.ok()?
|
||||
.error_for_status()
|
||||
.ok()?
|
||||
.json()
|
||||
.await
|
||||
.ok()?;
|
||||
let entry = ["types", "typings"]
|
||||
.iter()
|
||||
.find_map(|key| manifest.get(key)?.as_str())
|
||||
.unwrap_or("index.d.ts")
|
||||
.trim_start_matches("./");
|
||||
let types = fetch(&format!("{base}/{entry}"))
|
||||
.await
|
||||
.ok()?
|
||||
.error_for_status()
|
||||
.ok()?
|
||||
.text()
|
||||
.await
|
||||
.ok()?;
|
||||
Some(format!("// /node_modules/{name}/{entry}\n{types}"))
|
||||
/// Where a package's files come from: the public CDN, or the workspace's npm proxy, which
|
||||
/// is the authoritative source once the instance names a registry of its own. Each falls
|
||||
/// back to the other.
|
||||
struct NpmSources<'a> {
|
||||
ctx: &'a Ctx<'a>,
|
||||
proxy_first: bool,
|
||||
}
|
||||
|
||||
async fn npm_search(query: &str) -> Result<Vec<Value>, String> {
|
||||
impl NpmSources<'_> {
|
||||
async fn new<'a>(ctx: &'a Ctx<'a>) -> NpmSources<'a> {
|
||||
let proxy_first = ctx
|
||||
.get(&ctx.ws("npm_proxy/config"))
|
||||
.await
|
||||
.is_ok_and(|config| truthy(config.get("registry_configured")));
|
||||
NpmSources { ctx, proxy_first }
|
||||
}
|
||||
|
||||
async fn json(&self, cdn: String, proxy: String) -> Option<Value> {
|
||||
let via_cdn = || async {
|
||||
let response = fetch(&cdn).await.ok()?.error_for_status().ok()?;
|
||||
response.json::<Value>().await.ok()
|
||||
};
|
||||
let via_proxy = || async { self.ctx.get(&self.ctx.ws(&proxy)).await.ok() };
|
||||
if self.proxy_first {
|
||||
match via_proxy().await {
|
||||
Some(v) => Some(v),
|
||||
None => via_cdn().await,
|
||||
}
|
||||
} else {
|
||||
match via_cdn().await {
|
||||
Some(v) => Some(v),
|
||||
None => via_proxy().await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn text(&self, cdn: String, proxy: String) -> Option<String> {
|
||||
let via_cdn = || async {
|
||||
let response = fetch(&cdn).await.ok()?.error_for_status().ok()?;
|
||||
response.text().await.ok()
|
||||
};
|
||||
let via_proxy = || async {
|
||||
self.ctx
|
||||
.request("GET", &self.ctx.ws(&proxy), None)
|
||||
.await
|
||||
.ok()
|
||||
};
|
||||
if self.proxy_first {
|
||||
match via_proxy().await {
|
||||
Some(v) => Some(v),
|
||||
None => via_cdn().await,
|
||||
}
|
||||
} else {
|
||||
match via_cdn().await {
|
||||
Some(v) => Some(v),
|
||||
None => via_proxy().await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `tag` as an exact version; one with two dots already is one.
|
||||
async fn version(&self, module: &str, tag: &str) -> Option<String> {
|
||||
if tag.split('.').count() >= 3 {
|
||||
return Some(tag.to_string());
|
||||
}
|
||||
let resolved = self
|
||||
.json(
|
||||
format!("https://data.jsdelivr.com/v1/package/resolve/npm/{module}@{tag}"),
|
||||
format!("npm_proxy/resolve/{}?tag={}", enc(module), enc(tag)),
|
||||
)
|
||||
.await?;
|
||||
resolved.get("version")?.as_str().map(String::from)
|
||||
}
|
||||
|
||||
/// The `.d.ts` files of `module` at `version`, in the order its file tree lists them.
|
||||
async fn dts_files(&self, module: &str, version: &str) -> Option<Vec<String>> {
|
||||
let tree = self
|
||||
.json(
|
||||
format!("https://data.jsdelivr.com/v1/package/npm/{module}@{version}/flat"),
|
||||
format!("npm_proxy/filetree/{}/{}", enc(module), enc(version)),
|
||||
)
|
||||
.await?;
|
||||
Some(
|
||||
array(tree.get("files"))
|
||||
.iter()
|
||||
.filter_map(|f| f.get("name")?.as_str())
|
||||
.filter(|name| name.ends_with(".d.ts"))
|
||||
.map(String::from)
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// `@bla/foo` → `bla__foo`, the DefinitelyTyped name of a scoped package.
|
||||
fn dt_name(name: &str) -> String {
|
||||
match name.strip_prefix('@') {
|
||||
Some(scoped) if scoped.contains('/') => scoped.replacen('/', "__", 1),
|
||||
_ => name.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every declaration file of the package, or of its `@types` package when it ships none,
|
||||
/// each headed by the path it would have under `node_modules`.
|
||||
/// Files fetched at once, as the browser's type acquisition did.
|
||||
const NPM_TYPES_CONCURRENCY: usize = 6;
|
||||
|
||||
/// The package's declarations joined in order, fetched only until they reach `limit`
|
||||
/// characters: only that head is returned, and `@types/lodash` alone has hundreds of files.
|
||||
async fn npm_package_types(
|
||||
sources: &NpmSources<'_>,
|
||||
name: &str,
|
||||
version: &str,
|
||||
limit: usize,
|
||||
) -> String {
|
||||
let mut module = name.to_string();
|
||||
let mut prefix = format!("/node_modules/{name}");
|
||||
let mut version = match sources.version(name, version).await {
|
||||
Some(version) => version,
|
||||
None => return String::new(),
|
||||
};
|
||||
let mut files = sources.dts_files(name, &version).await.unwrap_or_default();
|
||||
if files.is_empty() {
|
||||
module = format!("@types/{}", dt_name(name));
|
||||
prefix = format!("/node_modules/@types/{}", dt_name(name));
|
||||
let Some(dt_version) = sources.version(&module, "latest").await else {
|
||||
return String::new();
|
||||
};
|
||||
version = dt_version;
|
||||
files = sources
|
||||
.dts_files(&module, &version)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
}
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
for batch in files.chunks(NPM_TYPES_CONCURRENCY) {
|
||||
let contents = join_all(batch.iter().map(|file| {
|
||||
sources.text(
|
||||
format!("https://cdn.jsdelivr.net/npm/{module}@{version}{file}"),
|
||||
format!("npm_proxy/file/{}/{}{file}", enc(&module), enc(&version)),
|
||||
)
|
||||
}))
|
||||
.await;
|
||||
parts.extend(
|
||||
batch
|
||||
.iter()
|
||||
.zip(contents)
|
||||
.filter_map(|(file, code)| Some(format!("// {prefix}{file}\n{}", code?))),
|
||||
);
|
||||
if js_len(&parts.join("\n\n")) >= limit {
|
||||
break;
|
||||
}
|
||||
}
|
||||
parts.join("\n\n")
|
||||
}
|
||||
|
||||
fn confident_npm_matches(objects: &[Value]) -> Vec<&Value> {
|
||||
let score = |o: &Value| o.get("searchScore").and_then(Value::as_f64).unwrap_or(0.0);
|
||||
let best = objects.iter().map(score).fold(0.0, f64::max);
|
||||
objects
|
||||
.iter()
|
||||
.filter(|o| score(o) >= best * NPM_RUNNER_UP_SHARE)
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn npm_search(ctx: &Ctx<'_>, query: &str, limit: usize) -> Result<Vec<Value>, String> {
|
||||
let data: Value = fetch(&format!(
|
||||
"https://registry.npmjs.org/-/v1/search?text={}&size=2",
|
||||
enc(query)
|
||||
@@ -399,41 +563,36 @@ async fn npm_search(query: &str) -> Result<Vec<Value>, String> {
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
let packages = data
|
||||
let objects = data
|
||||
.get("objects")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or("no `objects` in the registry answer")?
|
||||
.iter()
|
||||
.filter(|o| {
|
||||
o.get("searchScore").and_then(Value::as_f64).unwrap_or(0.0) >= NPM_SCORE_THRESHOLD
|
||||
})
|
||||
.filter_map(|o| {
|
||||
let package = o.get("package")?;
|
||||
Some((
|
||||
package.get("name")?.as_str()?,
|
||||
package.get("version").and_then(Value::as_str),
|
||||
))
|
||||
});
|
||||
.ok_or("no `objects` in the registry answer")?;
|
||||
let packages = confident_npm_matches(objects).into_iter().filter_map(|o| {
|
||||
let package = o.get("package")?;
|
||||
Some((
|
||||
package.get("name")?.as_str()?,
|
||||
package.get("version").and_then(Value::as_str),
|
||||
))
|
||||
});
|
||||
let sources = &NpmSources::new(ctx).await;
|
||||
Ok(join_all(packages.map(|(name, version)| async move {
|
||||
let documentation = match fetch(&format!("https://unpkg.com/{name}/readme.md")).await {
|
||||
Ok(response) => response.text().await.unwrap_or_default(),
|
||||
Err(_) => String::new(),
|
||||
};
|
||||
let types = npm_package_types(name, version.unwrap_or("latest"))
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let types = npm_package_types(sources, name, version.unwrap_or("latest"), limit).await;
|
||||
json!({
|
||||
"package": name,
|
||||
"documentation": take_chars(&documentation, NPM_TEXT_LIMIT),
|
||||
"types": take_chars(&types, NPM_TEXT_LIMIT),
|
||||
"documentation": js_head(&documentation, limit),
|
||||
"types": js_head(&types, limit),
|
||||
})
|
||||
}))
|
||||
.await)
|
||||
}
|
||||
|
||||
async fn search_npm_packages(args: &Value) -> ToolResult {
|
||||
async fn search_npm_packages(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
let query = str_arg(args, "query")?;
|
||||
Ok(match npm_search(query).await {
|
||||
Ok(match npm_search(ctx, query, NPM_TEXT_LIMIT).await {
|
||||
Ok(results) => Value::Array(results).to_string(),
|
||||
Err(e) => {
|
||||
tracing::warn!("npm package search failed: {e}");
|
||||
@@ -454,7 +613,10 @@ fn docs_text(result: Result<Value, String>, action: &str) -> String {
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_string(),
|
||||
Err(e) => format!("Failed to {action}: {e}, pursuing with the user request..."),
|
||||
Err(e) => format!(
|
||||
"Failed to {action}: {}, pursuing with the user request...",
|
||||
api_message(&e)
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -466,6 +628,14 @@ async fn search_docs(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
);
|
||||
}
|
||||
let result = ctx.get(&format!("/docs/search?query={}", enc(query))).await;
|
||||
if let Ok(response) = &result {
|
||||
let mut facts = Map::new();
|
||||
facts.insert(
|
||||
"result_count".into(),
|
||||
array(response.get("results")).len().into(),
|
||||
);
|
||||
ctx.effect(Effect::Facts(facts));
|
||||
}
|
||||
Ok(docs_text(result, "search documentation"))
|
||||
}
|
||||
|
||||
@@ -661,7 +831,7 @@ async fn create_folder(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
"success": true,
|
||||
"message": format!("Created folder `f/{name}`. You can now write items to `f/{name}/<name>`.")
|
||||
}),
|
||||
Err(error) => json!({ "success": false, "error": error }),
|
||||
Err(error) => json!({ "success": false, "error": api_message(&error) }),
|
||||
}
|
||||
.to_string(),
|
||||
)
|
||||
@@ -671,6 +841,25 @@ async fn create_folder(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn npm_matches_are_judged_against_the_best_one() {
|
||||
let names = |scores: &[f64]| {
|
||||
let objects: Vec<Value> = scores
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, s)| json!({ "searchScore": s, "package": { "name": i.to_string() } }))
|
||||
.collect();
|
||||
confident_npm_matches(&objects)
|
||||
.iter()
|
||||
.map(|o| o["package"]["name"].as_str().unwrap().to_string())
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
// A descriptive query's right answer scores a few hundred; a weak runner-up is dropped.
|
||||
assert_eq!(names(&[815.0, 454.0]), ["0"]);
|
||||
assert_eq!(names(&[419.0, 384.0]), ["0", "1"]);
|
||||
assert!(names(&[]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggestions_rank_by_matched_words() {
|
||||
let integrations = vec![
|
||||
@@ -690,6 +879,12 @@ mod tests {
|
||||
["salesforce"]
|
||||
);
|
||||
assert_eq!(suggest_hub_integrations(&integrations, "s3 bucket"), ["s3"]);
|
||||
// With no display name from the hub, the slug reads as the frontend labels it.
|
||||
let unnamed = vec![json!({ "name": "gcloud", "display_name": null })];
|
||||
assert_eq!(
|
||||
suggest_hub_integrations(&unnamed, "deploy to google cloud"),
|
||||
["gcloud"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
+228
-180
@@ -1,30 +1,46 @@
|
||||
//! The Windmill MCP server's toolset (`/api/mcp`, tokens with `mcp:all`): an AI session's toolset, for a client
|
||||
//! outside the Windmill UI.
|
||||
//! The AI session's GLOBAL toolset, run on the server for both of its callers: the
|
||||
//! in-app chat (`POST /w/{workspace}/ai_session_tools/{name}`) and the Windmill MCP
|
||||
//! server (`/api/mcp`, tokens with `mcp:all`).
|
||||
//!
|
||||
//! Everything a model reads here — tool names, descriptions, input schemas, the
|
||||
//! instructions, the `get_instructions` texts — is generated from the session's own
|
||||
//! definitions into `gen/` (`npm run gen:mcp-session` in `frontend/`). What a tool
|
||||
//! *does* is written here, mirroring its session counterpart in
|
||||
//! `frontend/src/lib/components/copilot/chat/global/core.ts`: a change to one side's
|
||||
//! behaviour belongs on the other.
|
||||
//! *does* is written here once; the chat keeps only what needs a browser (cards,
|
||||
//! confirmations, the run form, the open editor).
|
||||
//!
|
||||
//! A tool acts through the API as the caller, the way the session's does, so every
|
||||
//! permission check is the API's own. It calls the server's router in-process rather
|
||||
//! than over a socket.
|
||||
//! A tool acts through the API as the caller, so every permission check is the API's
|
||||
//! own. It calls the server's router in-process rather than over a socket.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Map, Value};
|
||||
use windmill_mcp::server::{
|
||||
BackendResult, CallToolResult, ContentBlock, ErrorData, MetaObject, SessionAccess, Tool,
|
||||
ToolAnnotations,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value};
|
||||
use windmill_common::auth::create_jwt_token;
|
||||
|
||||
use crate::db::ApiAuthed;
|
||||
|
||||
use super::utils::{mint_caller_jwt, send_as_caller};
|
||||
pub(crate) mod chat;
|
||||
|
||||
/// What a caller may do with the toolset. An MCP token sets it from its scopes; the chat
|
||||
/// is always `Full`, its own gating running before a tool is called.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[cfg_attr(not(feature = "mcp"), allow(dead_code))]
|
||||
pub(crate) enum SessionAccess {
|
||||
ReadOnly,
|
||||
ReadAndRun,
|
||||
Full,
|
||||
}
|
||||
|
||||
/// Which caller a tool runs for, at the few spots where the two genuinely differ.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Surface {
|
||||
Mcp,
|
||||
Chat,
|
||||
}
|
||||
|
||||
/// The largest tool result the MCP runner passes on whole; it truncates beyond it.
|
||||
pub(crate) const MAX_TOOL_RESULT_BYTES: usize = 87_500;
|
||||
|
||||
/// Each running server's fully layered router, by its `base_internal_url`. Keyed rather
|
||||
/// than global because the backend tests run one server per test in a single process,
|
||||
@@ -42,11 +58,13 @@ pub(crate) fn register_router(base_internal_url: &str, router: Option<axum::Rout
|
||||
};
|
||||
}
|
||||
|
||||
mod ai_providers;
|
||||
mod apps;
|
||||
mod data;
|
||||
mod deploy;
|
||||
mod flows;
|
||||
mod guidance;
|
||||
#[cfg(feature = "mcp")]
|
||||
mod instructions;
|
||||
mod items;
|
||||
mod misc;
|
||||
@@ -55,13 +73,15 @@ mod settings;
|
||||
mod views;
|
||||
mod workspace;
|
||||
|
||||
pub(super) use instructions::{
|
||||
#[cfg(feature = "mcp")]
|
||||
pub(crate) use instructions::{
|
||||
generic_session_instructions, session_instructions, workspace_context,
|
||||
};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ToolDef {
|
||||
name: String,
|
||||
#[cfg_attr(not(feature = "mcp"), allow(dead_code))]
|
||||
description: String,
|
||||
parameters: Map<String, Value>,
|
||||
read_only: bool,
|
||||
@@ -108,6 +128,7 @@ const EDITOR_ONLY: &[&str] = &[
|
||||
/// live datatable, run code, cancel a job, delete work, or replace a draft's content, which
|
||||
/// discarding the draft does not restore. Stands in for the session's confirmation card. The
|
||||
/// ChatGPT and Claude directories reject such a tool without this hint.
|
||||
#[cfg(any(test, feature = "mcp"))]
|
||||
const DESTRUCTIVE: &[&str] = &[
|
||||
"write_script",
|
||||
"edit_script",
|
||||
@@ -144,15 +165,11 @@ const DESTRUCTIVE: &[&str] = &[
|
||||
"delete_app_runnable",
|
||||
];
|
||||
|
||||
/// The destructive tools a card may call, each from a button the user presses. Every
|
||||
/// other destructive tool is hidden from cards: a card acts as the user with no one
|
||||
/// confirming.
|
||||
const CARD_ACTIONS: &[&str] = &["deploy_workspace_item", "cancel_job"];
|
||||
|
||||
/// Tools that reach a system outside Windmill on the workspace's behalf: running code can
|
||||
/// reach any system the workspace can, and `get_db_schema` connects to a resource's
|
||||
/// database, and `search_npm_packages` queries the npm registry, which Windmill does not
|
||||
/// control. Reading Windmill's own hub and docs does not count.
|
||||
#[cfg(any(test, feature = "mcp"))]
|
||||
const OPEN_WORLD: &[&str] = &[
|
||||
"search_npm_packages",
|
||||
"run_script",
|
||||
@@ -166,23 +183,6 @@ const OPEN_WORLD: &[&str] = &[
|
||||
"get_db_schema",
|
||||
];
|
||||
|
||||
/// A tool's display name, which Claude shows in its tool list and approval prompts.
|
||||
fn tool_title(name: &str) -> String {
|
||||
let words: Vec<String> = name
|
||||
.split('_')
|
||||
.map(|word| match word {
|
||||
"db" | "sql" | "json" => word.to_uppercase(),
|
||||
_ => word.to_string(),
|
||||
})
|
||||
.collect();
|
||||
let title = words.join(" ");
|
||||
let mut chars = title.chars();
|
||||
chars
|
||||
.next()
|
||||
.map(|first| first.to_uppercase().chain(chars).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Tools the session counts as reads that still start a job. A read-only token runs
|
||||
/// nothing on the tools server, so it runs nothing here either.
|
||||
const RUNS_A_JOB: &[&str] = &["get_db_schema"];
|
||||
@@ -202,6 +202,7 @@ fn allowed(def: &ToolDef, access: SessionAccess) -> bool {
|
||||
/// Each group's tools and its dispatcher, tried in order.
|
||||
macro_rules! groups {
|
||||
($($group:ident),*) => {
|
||||
#[cfg(any(test, feature = "mcp"))]
|
||||
fn implemented() -> impl Iterator<Item = &'static str> {
|
||||
std::iter::empty()$(.chain($group::TOOLS.iter().copied()))*
|
||||
}
|
||||
@@ -216,92 +217,53 @@ macro_rules! groups {
|
||||
}
|
||||
groups!(guidance, workspace, items, misc, flows, apps, runs, deploy, data, settings);
|
||||
|
||||
/// Claude clients keep an MCP result in context only up to a token budget well under the
|
||||
/// authoring references `get_instructions` returns, unless the tool raises it. Above the
|
||||
/// runner's own cap on a result, so that cap is the one that applies.
|
||||
fn result_size_meta() -> MetaObject {
|
||||
let mut meta = Map::new();
|
||||
meta.insert("anthropic/maxResultSizeChars".to_string(), 100_000.into());
|
||||
MetaObject(meta)
|
||||
/// A tool as a client lists it.
|
||||
#[cfg(feature = "mcp")]
|
||||
pub(crate) struct ToolInfo {
|
||||
pub name: &'static str,
|
||||
pub description: &'static str,
|
||||
pub parameters: &'static Map<String, Value>,
|
||||
pub read_only: bool,
|
||||
pub destructive: bool,
|
||||
pub open_world: bool,
|
||||
}
|
||||
|
||||
/// The MCP Apps view a client that renders them draws these tools' results in. It draws
|
||||
/// what the tool put in its result's `_meta` (`Ctx::view`), and acts by calling tools.
|
||||
/// Hosts cache a view by its URI: bump the version when a change breaks the `_meta` shape
|
||||
/// the deployed card reads.
|
||||
pub(super) const CARD_URI: &str = "ui://windmill/card-v1";
|
||||
const CARD_HTML: &str = include_str!("card.html");
|
||||
|
||||
/// The `ui://` views the session's tools render in, as `(uri, html)`.
|
||||
pub(super) fn session_views() -> &'static [(&'static str, &'static str)] {
|
||||
&[(CARD_URI, CARD_HTML)]
|
||||
}
|
||||
|
||||
pub(super) fn session_tools(access: SessionAccess) -> Vec<Tool> {
|
||||
/// The tools implemented here that `access` may call.
|
||||
#[cfg(feature = "mcp")]
|
||||
pub(crate) fn session_tools(access: SessionAccess) -> impl Iterator<Item = ToolInfo> {
|
||||
TOOL_DEFS
|
||||
.iter()
|
||||
.filter(|def| implemented().any(|name| name == def.name))
|
||||
.filter(|def| allowed(def, access))
|
||||
.filter(move |def| allowed(def, access))
|
||||
.map(|def| {
|
||||
let name = def.name.as_str();
|
||||
let mut meta = result_size_meta();
|
||||
let destructive = DESTRUCTIVE.contains(&name);
|
||||
if destructive && !CARD_ACTIONS.contains(&name) {
|
||||
meta.0
|
||||
.insert("ui".into(), json!({ "visibility": ["model"] }));
|
||||
ToolInfo {
|
||||
name,
|
||||
description: &def.description,
|
||||
parameters: &def.parameters,
|
||||
read_only: def.read_only && !RUNS_A_JOB.contains(&name),
|
||||
destructive: DESTRUCTIVE.contains(&name),
|
||||
open_world: OPEN_WORLD.contains(&name),
|
||||
}
|
||||
let title = tool_title(name);
|
||||
Tool::new(
|
||||
def.name.clone(),
|
||||
def.description.clone(),
|
||||
def.parameters.clone(),
|
||||
)
|
||||
.with_title(title.clone())
|
||||
.with_annotations(
|
||||
ToolAnnotations::with_title(title)
|
||||
.read_only(def.read_only && !RUNS_A_JOB.contains(&name))
|
||||
.destructive(destructive)
|
||||
.open_world(OPEN_WORLD.contains(&name)),
|
||||
)
|
||||
.with_meta(meta)
|
||||
})
|
||||
.chain(
|
||||
views::definitions()
|
||||
.into_iter()
|
||||
.filter(|(name, ..)| views::allowed(name, access))
|
||||
.map(|(name, description, schema)| {
|
||||
let mut meta = result_size_meta();
|
||||
meta.0
|
||||
.insert("ui".into(), json!({ "resourceUri": CARD_URI }));
|
||||
let Value::Object(schema) = schema else {
|
||||
unreachable!("a view tool's schema is an object")
|
||||
};
|
||||
let title = tool_title(name);
|
||||
Tool::new(name, description, schema)
|
||||
.with_title(title.clone())
|
||||
.with_annotations(
|
||||
ToolAnnotations::with_title(title)
|
||||
.read_only(true)
|
||||
.destructive(false)
|
||||
.open_world(false),
|
||||
)
|
||||
.with_meta(meta)
|
||||
}),
|
||||
)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What a tool hands back: the text the model reads, or the message of a failed call.
|
||||
pub(super) type ToolResult = Result<String, String>;
|
||||
|
||||
/// The caller, and the API reached as them.
|
||||
pub(super) struct Ctx<'a> {
|
||||
pub(crate) struct Ctx<'a> {
|
||||
pub auth: &'a ApiAuthed,
|
||||
pub w_id: &'a str,
|
||||
pub base_internal_url: &'a str,
|
||||
pub access: SessionAccess,
|
||||
/// The scheme and host the MCP client reached, when known.
|
||||
pub origin: Option<&'a str>,
|
||||
pub surface: Surface,
|
||||
/// What the chat sends beside a call; `None` for MCP.
|
||||
pub chat: Option<&'a chat::ChatContext>,
|
||||
/// What the call changed that the chat has to apply: its editors, cards and drafts.
|
||||
pub effects: std::sync::Mutex<Vec<chat::Effect>>,
|
||||
/// Minted once per tool call: every JWT the API sees is cached by the auth layer, and a
|
||||
/// tool can make dozens of calls, which would evict other users' cached sessions.
|
||||
pub jwt: tokio::sync::OnceCell<String>,
|
||||
@@ -310,6 +272,38 @@ pub(super) struct Ctx<'a> {
|
||||
pub view: std::sync::Mutex<Option<(&'static str, Value)>>,
|
||||
}
|
||||
|
||||
impl<'a> Ctx<'a> {
|
||||
pub(crate) fn new(
|
||||
auth: &'a ApiAuthed,
|
||||
w_id: &'a str,
|
||||
base_internal_url: &'a str,
|
||||
access: SessionAccess,
|
||||
) -> Self {
|
||||
Ctx {
|
||||
auth,
|
||||
w_id,
|
||||
base_internal_url,
|
||||
access,
|
||||
origin: None,
|
||||
surface: Surface::Mcp,
|
||||
chat: None,
|
||||
effects: Default::default(),
|
||||
jwt: Default::default(),
|
||||
view: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Hand the chat something to apply. A no-op for MCP, which has no editor.
|
||||
pub(super) fn effect(&self, effect: chat::Effect) {
|
||||
if self.surface == Surface::Chat {
|
||||
self.effects.lock().unwrap().push(effect);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The total timeout of the HTTP client the in-process router replaces.
|
||||
const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
|
||||
|
||||
impl Ctx<'_> {
|
||||
/// Set what the card draws of this call, replacing what an inner step set.
|
||||
pub fn set_view(&self, key: &'static str, value: Value) {
|
||||
@@ -318,6 +312,20 @@ impl Ctx<'_> {
|
||||
|
||||
/// Call the API as the caller. `path` follows `/api`; a non-2xx answer is the error.
|
||||
pub async fn request(&self, method: &str, path: &str, body: Option<Value>) -> ToolResult {
|
||||
self.request_within(method, path, body, REQUEST_TIMEOUT)
|
||||
.await
|
||||
}
|
||||
|
||||
/// `request` for a route that waits on jobs of its own, like the datatable migration
|
||||
/// routes: each job is bounded server-side, so the default budget would cut a long one
|
||||
/// off midway.
|
||||
pub async fn request_within(
|
||||
&self,
|
||||
method: &str,
|
||||
path: &str,
|
||||
body: Option<Value>,
|
||||
timeout: std::time::Duration,
|
||||
) -> ToolResult {
|
||||
let url = guarded_url(self.base_internal_url, self.w_id, method, path, self.access)?;
|
||||
// No route scope: this server only admits `mcp:all`, several routes (hub, embeddings)
|
||||
// map to none, and `guarded_url` is what keeps a call on its route. The tag fence
|
||||
@@ -337,17 +345,18 @@ impl Ctx<'_> {
|
||||
.get(self.base_internal_url)
|
||||
.cloned();
|
||||
let (status, text) = match router {
|
||||
Some(router) => self.call_router(router, method, &url, body, scopes).await?,
|
||||
None => {
|
||||
let response = send_as_caller(method, &url, self.w_id, self.auth, body, scopes)
|
||||
.await
|
||||
.map_err(|e| e.message.to_string())?;
|
||||
let status = response.status();
|
||||
(status, response.text().await.map_err(|e| e.to_string())?)
|
||||
Some(router) => {
|
||||
self.call_router(router, method, &url, body, scopes, timeout)
|
||||
.await?
|
||||
}
|
||||
None => self.call_http(method, &url, body, scopes, timeout).await?,
|
||||
};
|
||||
if status.is_success() {
|
||||
Ok(text)
|
||||
} else if text.trim().is_empty() {
|
||||
// What a browser's request reports for an answer with no body.
|
||||
let reason = status.canonical_reason().unwrap_or_default();
|
||||
Err(format!("{}: {reason}", status.as_u16()))
|
||||
} else {
|
||||
Err(format!("{}: {}", status.as_u16(), text))
|
||||
}
|
||||
@@ -362,6 +371,7 @@ impl Ctx<'_> {
|
||||
url: &str,
|
||||
body: Option<Value>,
|
||||
scopes: Option<Vec<String>>,
|
||||
timeout: std::time::Duration,
|
||||
) -> Result<(http::StatusCode, String), String> {
|
||||
use tower::ServiceExt;
|
||||
let parsed = reqwest::Url::parse(url).map_err(|e| e.to_string())?;
|
||||
@@ -376,7 +386,7 @@ impl Ctx<'_> {
|
||||
.jwt
|
||||
.get_or_try_init(|| mint_caller_jwt(self.w_id, self.auth, scopes))
|
||||
.await
|
||||
.map_err(|e| e.message.to_string())?;
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut request = http::Request::builder()
|
||||
.method(method)
|
||||
.uri(uri)
|
||||
@@ -389,8 +399,7 @@ impl Ctx<'_> {
|
||||
None => axum::body::Body::empty(),
|
||||
};
|
||||
let request = request.body(body).map_err(|e| e.to_string())?;
|
||||
// The total timeout of the HTTP client this replaces.
|
||||
tokio::time::timeout(std::time::Duration::from_secs(30), async {
|
||||
tokio::time::timeout(timeout, async {
|
||||
let response = router.oneshot(request).await.map_err(|e| e.to_string())?;
|
||||
let status = response.status();
|
||||
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
|
||||
@@ -402,6 +411,36 @@ impl Ctx<'_> {
|
||||
.map_err(|_| format!("Failed to execute request: {method} {url} timed out"))?
|
||||
}
|
||||
|
||||
/// `request` over HTTP, for a server whose router is not registered.
|
||||
async fn call_http(
|
||||
&self,
|
||||
method: &str,
|
||||
url: &str,
|
||||
body: Option<Value>,
|
||||
scopes: Option<Vec<String>>,
|
||||
timeout: std::time::Duration,
|
||||
) -> Result<(http::StatusCode, String), String> {
|
||||
let method = http::Method::from_bytes(method.as_bytes()).map_err(|e| e.to_string())?;
|
||||
let token = self
|
||||
.jwt
|
||||
.get_or_try_init(|| mint_caller_jwt(self.w_id, self.auth, scopes))
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut request = crate::HTTP_CLIENT
|
||||
.request(method, url)
|
||||
.header("Authorization", format!("Bearer {token}"))
|
||||
.timeout(timeout);
|
||||
if let Some(body) = body {
|
||||
request = request.json(&body);
|
||||
}
|
||||
let response = request
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to execute request: {e}"))?;
|
||||
let status = response.status();
|
||||
Ok((status, response.text().await.map_err(|e| e.to_string())?))
|
||||
}
|
||||
|
||||
pub async fn get(&self, path: &str) -> Result<Value, String> {
|
||||
let text = self.request("GET", path, None).await?;
|
||||
serde_json::from_str(&text).map_err(|e| format!("unexpected response from {path}: {e}"))
|
||||
@@ -424,6 +463,12 @@ impl Ctx<'_> {
|
||||
format!("/w/{}/{}", self.w_id, rest)
|
||||
}
|
||||
|
||||
/// `page_url` for an MCP client only: the chat shows what a tool made or ran in its own
|
||||
/// cards and panel instead.
|
||||
pub fn link(&self, page: &str) -> Option<String> {
|
||||
(self.surface == Surface::Mcp).then(|| self.page_url(page))
|
||||
}
|
||||
|
||||
/// A Windmill page in this workspace, as a link the user can open: an external client
|
||||
/// has no preview panel, so a link is how it shows what a tool made or ran.
|
||||
pub fn page_url(&self, page: &str) -> String {
|
||||
@@ -637,57 +682,92 @@ pub(super) fn matches_glob(subject: &str, glob: &str) -> bool {
|
||||
regex::Regex::new(&pattern).is_ok_and(|re| re.is_match(subject))
|
||||
}
|
||||
|
||||
/// A generated session tool, refused when the token's access does not cover it.
|
||||
async fn call_generated_tool(ctx: &Ctx<'_>, name: &str, args: &Value) -> BackendResult<ToolResult> {
|
||||
/// A JWT that acts as `api_authed`, carrying `scopes`; `None` is the caller's full rights.
|
||||
pub(crate) async fn mint_caller_jwt(
|
||||
workspace_id: &str,
|
||||
api_authed: &ApiAuthed,
|
||||
scopes: Option<Vec<String>>,
|
||||
) -> windmill_common::error::Result<String> {
|
||||
// Carry the caller's job provenance into the JWT: a job's WM_TOKEN is capped at
|
||||
// workspace admin (GHSA-hfh4-cx4h-3fcr), and dropping `job_id` here would re-mint an
|
||||
// uncapped token that satisfies require_super_admin / require_devops_role.
|
||||
// A browser caller stays a session: runs, trigger history and schedules attribute a
|
||||
// session's actions to the UI, and anything else to the API (`webhook`).
|
||||
create_jwt_token(
|
||||
windmill_common::db::Authed::from(api_authed.clone()),
|
||||
workspace_id,
|
||||
3600,
|
||||
api_authed.job_id,
|
||||
api_authed.is_session_token.then(|| "session".to_string()),
|
||||
None,
|
||||
scopes,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Why a call was refused before the tool ran.
|
||||
pub(crate) enum CallRefused {
|
||||
UnknownTool(String),
|
||||
NotAllowed(String),
|
||||
NotAvailable(String),
|
||||
}
|
||||
|
||||
/// What the model reads, and whether the call failed.
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct ToolOutcome {
|
||||
pub text: String,
|
||||
pub is_error: bool,
|
||||
}
|
||||
|
||||
/// The card tools only MCP Apps clients draw; the chat draws its own cards.
|
||||
#[cfg(feature = "mcp")]
|
||||
pub(crate) use views::{allowed as view_allowed, definitions as view_definitions};
|
||||
|
||||
pub(crate) async fn call_session_tool(
|
||||
ctx: &Ctx<'_>,
|
||||
name: &str,
|
||||
args: Value,
|
||||
) -> Result<ToolOutcome, CallRefused> {
|
||||
if ctx.surface == Surface::Mcp && views::TOOLS.contains(&name) {
|
||||
return Ok(outcome(views::call(ctx, name, &args).await));
|
||||
}
|
||||
let result = call_generated_tool(ctx, name, &args).await?;
|
||||
Ok(outcome(result))
|
||||
}
|
||||
|
||||
/// A generated session tool, refused when the caller's access does not cover it.
|
||||
async fn call_generated_tool(
|
||||
ctx: &Ctx<'_>,
|
||||
name: &str,
|
||||
args: &Value,
|
||||
) -> Result<ToolResult, CallRefused> {
|
||||
let Some(def) = TOOL_DEFS.iter().find(|def| def.name == name) else {
|
||||
return Err(ErrorData::invalid_params(
|
||||
format!("Unknown tool '{name}'"),
|
||||
None,
|
||||
));
|
||||
return Err(CallRefused::UnknownTool(format!("Unknown tool '{name}'")));
|
||||
};
|
||||
if !allowed(def, ctx.access) {
|
||||
let token = match ctx.access {
|
||||
SessionAccess::ReadAndRun => "can only read and run deployed scripts and flows",
|
||||
_ => "is read-only",
|
||||
};
|
||||
return Err(ErrorData::invalid_request(
|
||||
format!("Tool '{name}' changes or runs something, and this token {token}"),
|
||||
None,
|
||||
));
|
||||
return Err(CallRefused::NotAllowed(format!(
|
||||
"Tool '{name}' changes or runs something, and this token {token}"
|
||||
)));
|
||||
}
|
||||
let Some(result) = dispatch(ctx, name, args).await else {
|
||||
return Err(ErrorData::invalid_params(
|
||||
format!("Tool '{name}' is not available on this server"),
|
||||
None,
|
||||
));
|
||||
};
|
||||
Ok(result)
|
||||
dispatch(ctx, name, args).await.ok_or_else(|| {
|
||||
CallRefused::NotAvailable(format!("Tool '{name}' is not available on this server"))
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn call_session_tool(
|
||||
ctx: &Ctx<'_>,
|
||||
name: &str,
|
||||
args: Value,
|
||||
) -> BackendResult<CallToolResult> {
|
||||
let result = if views::TOOLS.contains(&name) {
|
||||
views::call(ctx, name, &args).await
|
||||
} else {
|
||||
call_generated_tool(ctx, name, &args).await?
|
||||
};
|
||||
windmill_common::feature_usage::log_feature_usage("mcp_workspace", "tool_call", name);
|
||||
let mut result = match result {
|
||||
Ok(text) => CallToolResult::success(vec![ContentBlock::text(text)]),
|
||||
fn outcome(result: ToolResult) -> ToolOutcome {
|
||||
match result {
|
||||
Ok(text) => ToolOutcome { text, is_error: false },
|
||||
// Without the status code `Ctx` prefixes an API failure with, as the session reads it.
|
||||
Err(message) => {
|
||||
let body = workspace::api_message(&message);
|
||||
let text = if body.is_empty() { &message } else { body };
|
||||
CallToolResult::error(vec![ContentBlock::text(text.to_string())])
|
||||
ToolOutcome { text: text.to_string(), is_error: true }
|
||||
}
|
||||
};
|
||||
if let Some((key, view)) = ctx.view.lock().unwrap().take() {
|
||||
result.meta = Some(MetaObject(Map::from_iter([(key.to_string(), view)])));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -728,38 +808,6 @@ mod tests {
|
||||
assert!(url("POST", "/w/ws/variables/create", ReadOnly).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_card_can_call_a_destructive_tool_but_deploy_and_cancel() {
|
||||
for tool in session_tools(SessionAccess::Full) {
|
||||
let name = tool.name.as_ref();
|
||||
if DESTRUCTIVE.contains(&name) {
|
||||
let ui = tool.meta.as_ref().and_then(|m| m.0.get("ui"));
|
||||
let model_only = ui == Some(&json!({ "visibility": ["model"] }));
|
||||
assert_eq!(
|
||||
model_only,
|
||||
!matches!(name, "deploy_workspace_item" | "cancel_job"),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The ChatGPT directory wants every hint explicit, and Claude's a title on every tool.
|
||||
#[test]
|
||||
fn every_session_tool_has_a_title_and_explicit_hints() {
|
||||
for tool in session_tools(SessionAccess::Full) {
|
||||
let a = tool.annotations.as_ref().expect("annotations");
|
||||
assert!(tool.title.is_some() && a.title.is_some(), "{}", tool.name);
|
||||
assert!(
|
||||
a.read_only_hint.is_some()
|
||||
&& a.destructive_hint.is_some()
|
||||
&& a.open_world_hint.is_some(),
|
||||
"{}",
|
||||
tool.name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_session_tool_is_implemented_or_editor_only() {
|
||||
let implemented: Vec<&str> = implemented().collect();
|
||||
@@ -0,0 +1,120 @@
|
||||
{
|
||||
"//": "How a run's arguments are settled, which the chat does in the browser ($lib/components/job_args.ts, secretArgUtils.ts) and MCP on the server (runs.rs). Both test suites read this file, so a change on one side only fails. Each expectation applies its step to `args` alone. A minted variable is named <minted>.",
|
||||
"cases": [
|
||||
{
|
||||
"name": "undeclared arguments are dropped and named",
|
||||
"schema": { "properties": { "a": { "type": "string" } } },
|
||||
"args": { "a": "x", "b": 1, "constructor": 2 },
|
||||
"declared": { "args": { "a": "x" }, "undeclared": ["b", "constructor"] }
|
||||
},
|
||||
{
|
||||
"name": "a schema without properties declares nothing",
|
||||
"schema": {},
|
||||
"args": { "a": "x" },
|
||||
"declared": { "args": {}, "undeclared": ["a"] }
|
||||
},
|
||||
{
|
||||
"name": "a disabled field takes its default, reported only when a different value was proposed",
|
||||
"schema": {
|
||||
"properties": {
|
||||
"locked": { "type": "string", "disabled": true, "default": "fixed" },
|
||||
"same": { "type": "object", "disabled": true, "default": { "k": [1, 2] } },
|
||||
"absent": { "type": "number", "disabled": true, "default": 3 },
|
||||
"no_default": { "type": "string", "disabled": true },
|
||||
"free": { "type": "string", "default": "d" }
|
||||
}
|
||||
},
|
||||
"args": { "locked": "mine", "same": { "k": [1, 2] }, "no_default": "kept", "free": "mine" },
|
||||
"disabled_defaults": {
|
||||
"args": {
|
||||
"locked": "fixed",
|
||||
"same": { "k": [1, 2] },
|
||||
"absent": 3,
|
||||
"no_default": "kept",
|
||||
"free": "mine"
|
||||
},
|
||||
"reset": ["locked"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "secrets are minted at every depth, and references and empty fields are left alone",
|
||||
"schema": {
|
||||
"properties": {
|
||||
"token": { "type": "string", "password": true },
|
||||
"creds": { "type": "object", "password": true, "properties": { "user": { "type": "string" } } },
|
||||
"nested": { "type": "object", "properties": { "inner": { "type": "string", "password": true } } },
|
||||
"rows": {
|
||||
"type": "array",
|
||||
"items": { "type": "object", "properties": { "key": { "type": "string", "password": true } } }
|
||||
},
|
||||
"variant": {
|
||||
"type": "object",
|
||||
"oneOf": [
|
||||
{ "properties": { "label": { "type": "string" } } },
|
||||
{ "properties": { "pin": { "type": "string", "password": true } } }
|
||||
]
|
||||
},
|
||||
"named": { "type": "string", "password": true },
|
||||
"named_object": { "type": "object", "password": true },
|
||||
"blank": { "type": "string", "password": true },
|
||||
"nothing": { "type": "string", "password": true },
|
||||
"plain": { "type": "string" }
|
||||
}
|
||||
},
|
||||
"args": {
|
||||
"token": "hunter2",
|
||||
"creds": { "user": "ada" },
|
||||
"nested": { "inner": "deep" },
|
||||
"rows": [{ "key": "k1" }, { "key": "$var:f/team/k2" }],
|
||||
"variant": { "pin": "1234" },
|
||||
"named": "$var:f/team/api_token",
|
||||
"named_object": "$var:f/team/creds",
|
||||
"blank": "",
|
||||
"nothing": null,
|
||||
"plain": "kept"
|
||||
},
|
||||
"secrets": {
|
||||
"args": {
|
||||
"token": "$var:<minted>",
|
||||
"creds": "$jsonvar:<minted>",
|
||||
"nested": { "inner": "$var:<minted>" },
|
||||
"rows": [{ "key": "$var:<minted>" }, { "key": "$var:f/team/k2" }],
|
||||
"variant": { "pin": "$var:<minted>" },
|
||||
"named": "$var:f/team/api_token",
|
||||
"named_object": "$jsonvar:f/team/creds",
|
||||
"blank": "",
|
||||
"nothing": null,
|
||||
"plain": "kept"
|
||||
},
|
||||
"stored": ["1234", "deep", "hunter2", "k1", "{\"user\":\"ada\"}"]
|
||||
},
|
||||
"redacted": {
|
||||
"token": "<hidden>",
|
||||
"creds": "<hidden>",
|
||||
"nested": { "inner": "<hidden>" },
|
||||
"rows": [{ "key": "<hidden>" }, { "key": "$var:f/team/k2" }],
|
||||
"variant": { "pin": "<hidden>" },
|
||||
"named": "$var:f/team/api_token",
|
||||
"named_object": "$var:f/team/creds",
|
||||
"blank": "",
|
||||
"plain": "kept"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "file bytes are replaced by their size",
|
||||
"schema": {
|
||||
"properties": {
|
||||
"doc": { "type": "string", "contentEncoding": "base64" },
|
||||
"docs": { "type": "array", "items": { "type": "string", "contentEncoding": "base64" } },
|
||||
"name": { "type": "string" }
|
||||
}
|
||||
},
|
||||
"args": {
|
||||
"doc": "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=",
|
||||
"docs": ["QUJD", "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWg=="],
|
||||
"name": "report.pdf"
|
||||
},
|
||||
"redacted": { "doc": "<file: 1 KB>", "docs": ["<file: 1 KB>", "<file: 1 KB>"], "name": "report.pdf" }
|
||||
}
|
||||
]
|
||||
}
|
||||
+821
-345
File diff suppressed because it is too large
Load Diff
+61
-20
@@ -2,8 +2,9 @@
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use super::chat::Effect;
|
||||
use super::workspace::api_message;
|
||||
use super::{array, js_head, js_len, js_str, str_arg, Ctx, ToolResult};
|
||||
use super::{array, js_head, js_len, js_str, str_arg, Ctx, Surface, ToolResult};
|
||||
|
||||
pub(super) const TOOLS: &[&str] = &["get_workspace_settings", "set_workspace_settings"];
|
||||
|
||||
@@ -65,37 +66,73 @@ fn parse_settings_yaml(text: &str) -> Result<Value, String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The dry run stands in for the session's confirmation card: it reports a no-op or an
|
||||
/// invalid document before anything is written.
|
||||
/// The dry run reports a no-op or an invalid document before anything is written: for MCP
|
||||
/// it stands in for the session's confirmation card, and the chat runs it alone, as a
|
||||
/// check-only call, before showing that card.
|
||||
async fn set_workspace_settings(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
let route = ctx.ws("workspaces/settings_document");
|
||||
let refuse = |label: String, text: String| {
|
||||
ctx.facts(json!({ "refused": label }));
|
||||
Ok(text)
|
||||
};
|
||||
let document = match parse_settings_yaml(str_arg(args, "yaml")?) {
|
||||
Ok(document) => document,
|
||||
Err(e) => return Ok(format!("Nothing was changed: {e}")),
|
||||
Err(e) if ctx.surface == Surface::Chat && !ctx.check_only() => return Err(e),
|
||||
Err(e) => {
|
||||
return refuse(
|
||||
format!("Invalid settings: {e}"),
|
||||
format!("Nothing was changed: {e}"),
|
||||
)
|
||||
}
|
||||
};
|
||||
let dry_run = json!({ "document": document, "replace": false, "dry_run": true });
|
||||
let dry_run = match ctx.post(&route, dry_run).await {
|
||||
Ok(result) => result,
|
||||
Err(e) => return Ok(format!("Nothing was changed: {}", api_message(&e))),
|
||||
};
|
||||
if array(dry_run.get("changes")).is_empty() {
|
||||
let warnings: Vec<String> = array(dry_run.get("warnings")).iter().map(js_str).collect();
|
||||
let warnings = if warnings.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" Warnings: {}", warnings.join(" "))
|
||||
// The chat's own check ran before its card, and the user confirmed what it showed.
|
||||
if ctx.surface == Surface::Mcp || ctx.check_only() {
|
||||
let dry_run = json!({ "document": document, "replace": false, "dry_run": true });
|
||||
let dry_run = match ctx.post(&route, dry_run).await {
|
||||
Ok(result) => result,
|
||||
Err(e) => {
|
||||
let e = api_message(&e);
|
||||
return refuse(
|
||||
format!("Invalid settings: {e}"),
|
||||
format!("Nothing was changed: {e}"),
|
||||
);
|
||||
}
|
||||
};
|
||||
return Ok(format!(
|
||||
"The settings already hold these values: nothing to change.{warnings}"
|
||||
));
|
||||
if array(dry_run.get("changes")).is_empty() {
|
||||
let warnings: Vec<String> = array(dry_run.get("warnings")).iter().map(js_str).collect();
|
||||
let warnings = if warnings.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" Warnings: {}", warnings.join(" "))
|
||||
};
|
||||
return refuse(
|
||||
"No settings change".to_string(),
|
||||
format!("The settings already hold these values: nothing to change.{warnings}"),
|
||||
);
|
||||
}
|
||||
if ctx.check_only() {
|
||||
ctx.facts(json!({ "changes": dry_run["changes"] }));
|
||||
return Ok(String::new());
|
||||
}
|
||||
}
|
||||
let applied = match ctx
|
||||
.post(&route, json!({ "document": document, "replace": false }))
|
||||
.await
|
||||
{
|
||||
Ok(result) => result,
|
||||
Err(e) => return Ok(json!({ "success": false, "error": api_message(&e) }).to_string()),
|
||||
Err(e) => {
|
||||
let error = api_message(&e);
|
||||
let mut failed = Map::new();
|
||||
failed.insert(
|
||||
"content".into(),
|
||||
json!("Failed to change workspace settings"),
|
||||
);
|
||||
failed.insert("error".into(), json!(error));
|
||||
ctx.effect(Effect::Status(failed));
|
||||
return Ok(json!({ "success": false, "error": error }).to_string());
|
||||
}
|
||||
};
|
||||
ctx.facts(json!({ "changes": applied["changes"] }));
|
||||
let keys: Vec<String> = array(applied.get("changes"))
|
||||
.iter()
|
||||
.map(|c| js_str(c.get("key").unwrap_or(&Value::Null)))
|
||||
@@ -105,7 +142,11 @@ async fn set_workspace_settings(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
out.insert(
|
||||
"message".into(),
|
||||
json!(format!(
|
||||
"These settings are now applied: {}.",
|
||||
"{} now applied: {}.",
|
||||
match ctx.surface {
|
||||
Surface::Chat => "The user approved and these settings are",
|
||||
Surface::Mcp => "These settings are",
|
||||
},
|
||||
keys.join(", ")
|
||||
)),
|
||||
);
|
||||
+6
-3
@@ -3,7 +3,9 @@
|
||||
//! the other tools, which draw nothing, and calls one of these when it means the user to
|
||||
//! see a result: a host draws a card for every call of a tool that has one.
|
||||
|
||||
use serde_json::{json, Value};
|
||||
#[cfg(feature = "mcp")]
|
||||
use serde_json::json;
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{deploy, runs, workspace, Ctx, SessionAccess, ToolResult};
|
||||
|
||||
@@ -11,7 +13,7 @@ pub(super) const TOOLS: &[&str] = &["show_run", "show_runs", "show_deploy_review
|
||||
|
||||
/// The review card's one action deploys, which only a full token may do: such a token is
|
||||
/// neither offered the tool nor answered when it calls it by name.
|
||||
pub(super) fn allowed(name: &str, access: SessionAccess) -> bool {
|
||||
pub(crate) fn allowed(name: &str, access: SessionAccess) -> bool {
|
||||
name != "show_deploy_review" || access == SessionAccess::Full
|
||||
}
|
||||
|
||||
@@ -32,7 +34,8 @@ pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult
|
||||
|
||||
/// Each tool as `(name, description, input schema)`. All only read: the review card's
|
||||
/// Deploy button calls `deploy_workspace_item`, which the token's own access gates.
|
||||
pub(super) fn definitions() -> [(&'static str, &'static str, Value); 4] {
|
||||
#[cfg(feature = "mcp")]
|
||||
pub(crate) fn definitions() -> [(&'static str, &'static str, Value); 4] {
|
||||
[
|
||||
(
|
||||
"show_run",
|
||||
+230
-65
@@ -4,9 +4,10 @@ use std::collections::HashMap;
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use super::chat::Effect;
|
||||
use super::{
|
||||
array, bool_arg, enc, is_not_found, js_len, js_str, non_null, opt_str_arg, pretty, put,
|
||||
str_arg, truthy, Ctx, ToolResult,
|
||||
str_arg, truthy, Ctx, Surface, ToolResult,
|
||||
};
|
||||
|
||||
pub(super) const TOOLS: &[&str] = &[
|
||||
@@ -294,11 +295,17 @@ pub(super) struct Draft {
|
||||
pub created_at: Option<String>,
|
||||
}
|
||||
|
||||
/// The caller's own draft named `path`. For the chat, a cell the browser holds is newer
|
||||
/// than the server's row and wins, the way the editor reads it.
|
||||
pub(super) async fn get_draft(
|
||||
ctx: &Ctx<'_>,
|
||||
kind: &str,
|
||||
path: &str,
|
||||
) -> Result<Option<Draft>, String> {
|
||||
let path = ctx.storage_path(kind, path);
|
||||
if let Some(value) = ctx.chat.and_then(|chat| chat.cell(kind, path)) {
|
||||
return Ok(Some(Draft { value: value.clone(), created_at: None }));
|
||||
}
|
||||
let row = ctx
|
||||
.get(&ctx.ws(&format!("drafts/get_own/{kind}/{}", path_enc(path))))
|
||||
.await?;
|
||||
@@ -312,6 +319,9 @@ pub(super) async fn get_draft(
|
||||
Ok(Some(Draft { value, created_at }))
|
||||
}
|
||||
|
||||
/// Save the caller's draft, or delete it with `None`. False on a conflict with a newer
|
||||
/// row. The chat saves through its editor's own draft store instead, after the call: it
|
||||
/// gets the write as an effect, and reports a conflict or failure itself.
|
||||
pub(super) async fn save_draft(
|
||||
ctx: &Ctx<'_>,
|
||||
kind: &str,
|
||||
@@ -320,6 +330,25 @@ pub(super) async fn save_draft(
|
||||
last_sync: Option<&str>,
|
||||
force: bool,
|
||||
) -> Result<bool, String> {
|
||||
if ctx.surface == Surface::Chat {
|
||||
let storage_path = ctx.storage_path(kind, path).to_string();
|
||||
ctx.effect(match value {
|
||||
Some(value) => Effect::DraftWrite {
|
||||
kind: kind.to_string(),
|
||||
storage_path,
|
||||
value: value.clone(),
|
||||
last_sync: last_sync.map(String::from),
|
||||
force,
|
||||
},
|
||||
None => Effect::DraftDelete {
|
||||
kind: kind.to_string(),
|
||||
storage_path,
|
||||
last_sync: last_sync.map(String::from),
|
||||
keep_live_editor: false,
|
||||
},
|
||||
});
|
||||
return Ok(true);
|
||||
}
|
||||
let mut body = Map::new();
|
||||
body.insert("value".into(), value.cloned().unwrap_or(Value::Null));
|
||||
if !force {
|
||||
@@ -335,12 +364,24 @@ pub(super) async fn save_draft(
|
||||
Ok(response.get("status").and_then(Value::as_str) != Some("conflict"))
|
||||
}
|
||||
|
||||
/// Delete the caller's draft. `keep_live_editor` leaves an editor open on it with its
|
||||
/// copy, detached from the row, as a deploy does.
|
||||
pub(super) async fn delete_draft(
|
||||
ctx: &Ctx<'_>,
|
||||
kind: &str,
|
||||
path: &str,
|
||||
last_sync: Option<&str>,
|
||||
keep_live_editor: bool,
|
||||
) -> Result<(), String> {
|
||||
if ctx.surface == Surface::Chat {
|
||||
ctx.effect(Effect::DraftDelete {
|
||||
kind: kind.to_string(),
|
||||
storage_path: ctx.storage_path(kind, path).to_string(),
|
||||
last_sync: last_sync.map(String::from),
|
||||
keep_live_editor,
|
||||
});
|
||||
return Ok(());
|
||||
}
|
||||
match save_draft(ctx, kind, path, None, last_sync, false).await {
|
||||
Ok(true) => Ok(()),
|
||||
Ok(false) => Err(format!(
|
||||
@@ -364,6 +405,7 @@ pub(super) async fn list_drafts(ctx: &Ctx<'_>) -> Result<Vec<Value>, String> {
|
||||
let Some((item_type, trigger_kind)) = item_type_of_kind(kind) else {
|
||||
continue;
|
||||
};
|
||||
let (path, live) = ctx.display_path(kind, path);
|
||||
let mut item = Map::new();
|
||||
item.insert("type".into(), json!(item_type));
|
||||
item.insert("path".into(), json!(path));
|
||||
@@ -380,8 +422,31 @@ pub(super) async fn list_drafts(ctx: &Ctx<'_>) -> Result<Vec<Value>, String> {
|
||||
if kind == "raw_app" {
|
||||
item.insert("rawApp".into(), json!(true));
|
||||
}
|
||||
if live {
|
||||
item.insert("isLiveDraft".into(), json!(true));
|
||||
}
|
||||
drafts.insert(item_key(item_type, path, trigger_kind), Value::Object(item));
|
||||
}
|
||||
// The browser's cells carry edits the rows may not have yet, and win.
|
||||
for cell in ctx
|
||||
.chat
|
||||
.map(|chat| chat.cells.as_slice())
|
||||
.unwrap_or_default()
|
||||
{
|
||||
let Some(Value::Object(mut item)) =
|
||||
shown_draft_item(ctx, &cell.kind, &cell.storage_path, &cell.value)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
item.shift_remove("value");
|
||||
item.shift_remove("schema");
|
||||
let text = |key: &str| item.get(key).and_then(Value::as_str).map(String::from);
|
||||
let (Some(item_type), Some(path)) = (text("type"), text("path")) else {
|
||||
continue;
|
||||
};
|
||||
let key = item_key(&item_type, &path, text("triggerKind").as_deref());
|
||||
drafts.insert(key, Value::Object(item));
|
||||
}
|
||||
Ok(drafts.into_iter().map(|(_, item)| item).collect())
|
||||
}
|
||||
|
||||
@@ -540,7 +605,24 @@ pub(super) async fn get_draft_item(
|
||||
let Some(draft) = get_draft(ctx, &kind, path).await? else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(draft_item(&kind, path, &draft.value).map(|item| (item, draft)))
|
||||
Ok(shown_draft_item(ctx, &kind, path, &draft.value).map(|item| (item, draft)))
|
||||
}
|
||||
|
||||
/// `draft_item` under the path the user sees: an open editor's own name for its draft,
|
||||
/// flagged as live.
|
||||
pub(super) fn shown_draft_item(
|
||||
ctx: &Ctx<'_>,
|
||||
kind: &str,
|
||||
path: &str,
|
||||
draft: &Value,
|
||||
) -> Option<Value> {
|
||||
let (shown, live) = ctx.display_path(kind, ctx.storage_path(kind, path));
|
||||
let mut item = draft_item(kind, shown, draft)?;
|
||||
if live {
|
||||
item.as_object_mut()?
|
||||
.insert("isLiveDraft".into(), json!(true));
|
||||
}
|
||||
Some(item)
|
||||
}
|
||||
|
||||
fn stash_inline_script(
|
||||
@@ -766,6 +848,7 @@ pub(super) fn summarize_app_value(value: &Value) -> Value {
|
||||
_ if !by_path => "inline",
|
||||
Some("flow") => "flow",
|
||||
Some("hubscript") => "hubscript",
|
||||
Some("agent") => "agent",
|
||||
_ => "script",
|
||||
};
|
||||
out.insert("type".into(), json!(run_type));
|
||||
@@ -869,7 +952,7 @@ pub(super) fn serialize_for_read(item: &Value, execution_mode: Option<Value>) ->
|
||||
let mut value = flow.get("value").cloned().unwrap_or_else(|| json!({}));
|
||||
if let (Some(groups), Some(value)) = (flow.get("groups"), value.as_object_mut()) {
|
||||
if groups.is_null() {
|
||||
value.remove("groups");
|
||||
value.shift_remove("groups");
|
||||
} else {
|
||||
value.insert("groups".into(), groups.clone());
|
||||
}
|
||||
@@ -1013,7 +1096,7 @@ pub(super) async fn persist_draft(
|
||||
) -> Result<Persist, String> {
|
||||
let kind = draft_kind(item_type, trigger_kind)
|
||||
.ok_or_else(|| format!("Unsupported draft type \"{item_type}\"."))?;
|
||||
let item = draft_item(&kind, path, value)
|
||||
let item = shown_draft_item(ctx, &kind, path, value)
|
||||
.ok_or_else(|| format!("Could not synthesize {item_type} draft \"{path}\"."))?;
|
||||
let failure = match save_draft(ctx, &kind, path, Some(value), last_sync, force).await {
|
||||
Ok(true) => return Ok(Persist::Saved(item)),
|
||||
@@ -1057,8 +1140,9 @@ pub(super) fn finish_draft_write(ctx: &Ctx<'_>, item: &Value, existed: bool) ->
|
||||
json!(format!("{verb} {item_type} \"{path}\" as a per-user draft (saved server-side, visible only to this user — not a deployed workspace item). It was not deployed.")),
|
||||
);
|
||||
let value = item.get("value").unwrap_or(&Value::Null);
|
||||
// The chat opens the draft in its own panel; an MCP client only has the link.
|
||||
if let Some(page) = draft_page(item_type, path, value) {
|
||||
out.insert("url".into(), json!(ctx.page_url(&page)));
|
||||
put(&mut out, "url", ctx.link(&page).map(Value::from));
|
||||
}
|
||||
// A flow is not echoed back: the model just sent it. A variable comes back redacted.
|
||||
match item_type {
|
||||
@@ -1246,7 +1330,13 @@ pub(super) fn unified_patch(
|
||||
fn deployed_item(item_type: &str, trigger_kind: Option<&str>, row: &Value) -> Value {
|
||||
let mut item = Map::new();
|
||||
item.insert("type".into(), json!(item_type));
|
||||
put(&mut item, "triggerKind", trigger_kind.map(Value::from));
|
||||
put(
|
||||
&mut item,
|
||||
"triggerKind",
|
||||
trigger_kind
|
||||
.filter(|_| item_type == "trigger")
|
||||
.map(Value::from),
|
||||
);
|
||||
put(&mut item, "path", row.get("path").cloned());
|
||||
let mut is_draft = false;
|
||||
match item_type {
|
||||
@@ -1313,8 +1403,29 @@ async fn list_workspace_items(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(50);
|
||||
let page = args.get("page").and_then(Value::as_u64);
|
||||
let prefix = opt_str_arg(args, "path_prefix");
|
||||
// Scoped, the session's folders are the default, one listing each; an explicit
|
||||
// path_prefix, "" included, overrides them.
|
||||
let scope_roots: &[String] = match prefix {
|
||||
None => ctx
|
||||
.chat
|
||||
.and_then(|chat| chat.scope_roots.as_deref())
|
||||
.unwrap_or_default(),
|
||||
Some(_) => &[],
|
||||
};
|
||||
let prefixes: Vec<Option<String>> = if scope_roots.is_empty() {
|
||||
vec![prefix.filter(|p| !p.is_empty()).map(str::to_string)]
|
||||
} else {
|
||||
scope_roots.iter().map(|root| Some(format!("{root}/"))).collect()
|
||||
};
|
||||
let per_page = limit.min(MAX_LIST_LIMIT);
|
||||
let page_number = page.unwrap_or(1).max(1);
|
||||
// Several folders read as one listing, folder after folder, so `limit` stays one cap per
|
||||
// type (per trigger kind for triggers): page N is rows (N-1)*limit..N*limit of each
|
||||
// concatenation, which takes every folder's first N*limit rows.
|
||||
let window = (prefixes.len() > 1)
|
||||
.then(|| (page_number - 1) * per_page..page_number * per_page);
|
||||
|
||||
let mut query = format!("per_page={}", limit.min(MAX_LIST_LIMIT));
|
||||
let mut query = format!("per_page={per_page}");
|
||||
if let Some(page) = page {
|
||||
query.push_str(&format!("&page={page}"));
|
||||
}
|
||||
@@ -1338,40 +1449,54 @@ async fn list_workspace_items(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(prefix) = prefix {
|
||||
query.push_str(&format!("&path_start={}", enc(prefix)));
|
||||
}
|
||||
|
||||
let mut by_key = Map::new();
|
||||
for item_type in ITEM_TYPES.iter().filter(|t| types.contains(t)) {
|
||||
let kinds: Vec<Option<&str>> = if *item_type == "trigger" {
|
||||
TRIGGER_KINDS.iter().map(|kind| Some(*kind)).collect()
|
||||
} else {
|
||||
vec![None]
|
||||
};
|
||||
let extra = if matches!(*item_type, "script" | "flow") {
|
||||
"&include_draft_only=true&without_description=true"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
for trigger_kind in kinds {
|
||||
let route = ctx.ws(&format!(
|
||||
"{}/list?{query}{extra}",
|
||||
service(item_type, trigger_kind)?
|
||||
));
|
||||
let rows = match ctx.get(&route).await {
|
||||
Ok(rows) => rows,
|
||||
// A trigger kind this build does not serve answers 404: skip that kind
|
||||
// alone. Any other failure is real.
|
||||
Err(e) if trigger_kind.is_some() && is_not_found(&e) => continue,
|
||||
Err(e) => return Err(e),
|
||||
// Each type's index into its concatenation across folders, per trigger kind for triggers.
|
||||
let mut index_by_kind: HashMap<String, u64> = HashMap::new();
|
||||
for prefix in &prefixes {
|
||||
for item_type in ITEM_TYPES.iter().filter(|t| types.contains(t)) {
|
||||
let kinds: Vec<Option<&str>> = if *item_type == "trigger" {
|
||||
TRIGGER_KINDS.iter().map(|kind| Some(*kind)).collect()
|
||||
} else {
|
||||
vec![None]
|
||||
};
|
||||
for row in array(Some(&rows)) {
|
||||
let path = row.get("path").and_then(Value::as_str).unwrap_or_default();
|
||||
by_key.insert(
|
||||
item_key(item_type, path, trigger_kind),
|
||||
deployed_item(item_type, trigger_kind, row),
|
||||
);
|
||||
let extra = if matches!(*item_type, "script" | "flow") {
|
||||
"&include_draft_only=true&without_description=true"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
for trigger_kind in kinds {
|
||||
let mut query = match &window {
|
||||
Some(window) => format!("per_page={}", window.end),
|
||||
None => query.clone(),
|
||||
};
|
||||
if let Some(prefix) = prefix {
|
||||
query.push_str(&format!("&path_start={}", enc(prefix)));
|
||||
}
|
||||
let route = ctx.ws(&format!(
|
||||
"{}/list?{query}{extra}",
|
||||
service(item_type, trigger_kind)?
|
||||
));
|
||||
let rows = match ctx.get(&route).await {
|
||||
Ok(rows) => rows,
|
||||
// A trigger kind this build does not serve answers 404: skip that kind
|
||||
// alone. Any other failure is real.
|
||||
Err(e) if trigger_kind.is_some() && is_not_found(&e) => continue,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let index = index_by_kind
|
||||
.entry(format!("{item_type}:{}", trigger_kind.unwrap_or_default()))
|
||||
.or_default();
|
||||
for row in array(Some(&rows)) {
|
||||
*index += 1;
|
||||
if window.as_ref().is_some_and(|w| !w.contains(&(*index - 1))) {
|
||||
continue;
|
||||
}
|
||||
let path = row.get("path").and_then(Value::as_str).unwrap_or_default();
|
||||
by_key.insert(
|
||||
item_key(item_type, path, trigger_kind),
|
||||
deployed_item(item_type, trigger_kind, row),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1380,6 +1505,7 @@ async fn list_workspace_items(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
// pages never repeat a page-1 item as its draft twin.
|
||||
if page.unwrap_or(1) == 1 {
|
||||
let mut count_by_type: HashMap<String, u64> = HashMap::new();
|
||||
let narrowing: Vec<&str> = prefixes.iter().flatten().map(String::as_str).collect();
|
||||
for draft in list_drafts(ctx).await? {
|
||||
let text = |key: &str| draft.get(key).and_then(Value::as_str);
|
||||
let (item_type, path) = (
|
||||
@@ -1391,11 +1517,13 @@ async fn list_workspace_items(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
}
|
||||
// A draft's staged name is often not where it is stored, and this pass is
|
||||
// the only source of draft-only rows under a prefix: either name may match.
|
||||
if let Some(prefix) = prefix {
|
||||
let staged = text("draftPath").is_some_and(|p| p.starts_with(prefix));
|
||||
if !path.starts_with(prefix) && !staged {
|
||||
continue;
|
||||
}
|
||||
let staged = text("draftPath");
|
||||
if !narrowing.is_empty()
|
||||
&& !narrowing.iter().any(|prefix| {
|
||||
path.starts_with(prefix) || staged.is_some_and(|p| p.starts_with(prefix))
|
||||
})
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let count = count_by_type.entry(item_type.to_string()).or_default();
|
||||
if *count >= limit {
|
||||
@@ -1425,7 +1553,15 @@ async fn list_workspace_items(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(pretty(&Value::Array(results)))
|
||||
let listed = pretty(&Value::Array(results));
|
||||
if scope_roots.is_empty() {
|
||||
return Ok(listed);
|
||||
}
|
||||
let folders: Vec<&str> = prefixes.iter().flatten().map(String::as_str).collect();
|
||||
Ok(format!(
|
||||
"Items under {}, where this session works. Pass path_prefix \"\" for the whole workspace.\n{listed}",
|
||||
folders.join(", ")
|
||||
))
|
||||
}
|
||||
|
||||
/// The card of one workspace item: what `read_workspace_item` returns, under a one-line
|
||||
@@ -1663,8 +1799,28 @@ async fn write_script_draft(
|
||||
content: &str,
|
||||
force: bool,
|
||||
) -> ToolResult {
|
||||
// A session builds pipeline nodes into the folder's pipeline draft; a script draft
|
||||
// written here never reaches the pipeline graph, and saving the pipeline drops it.
|
||||
if ctx.in_session() && windmill_common::assets::parse_pipeline_annotations(content).in_pipeline
|
||||
{
|
||||
let folder = path
|
||||
.strip_prefix("f/")
|
||||
.and_then(|rest| rest.split_once('/'))
|
||||
.map_or("<folder>", |(folder, _)| folder);
|
||||
return Err(format!(
|
||||
"\"{path}\" is a data pipeline node (its source starts with the pipeline annotation). In a session, pipeline nodes are not script drafts: call open_preview(kind=\"pipeline\", path=\"{folder}\") if that folder's pipeline editor is not open yet, then use build_pipeline_node (new node) or edit_pipeline_node (existing node). Nothing was written."
|
||||
));
|
||||
}
|
||||
ctx.saving_draft("script", path);
|
||||
let base = write_base(ctx, "script", path, None).await?;
|
||||
let existed = base.base.is_some();
|
||||
let before = base
|
||||
.base
|
||||
.as_ref()
|
||||
.and_then(|b| b.get("content"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
let mut draft = match base.base {
|
||||
Some(Value::Object(mut script)) => {
|
||||
if !base.from_draft {
|
||||
@@ -1697,17 +1853,21 @@ async fn write_script_draft(
|
||||
};
|
||||
// Inferred into the schema the base carries: its properties are the only copy of
|
||||
// what no parser emits (`password`, enums, formats, titles). Code that does not
|
||||
// parse keeps the schema as it was.
|
||||
let previous = draft
|
||||
.get("schema")
|
||||
.filter(|schema| truthy(schema.get("properties")))
|
||||
.cloned()
|
||||
.unwrap_or_else(empty_schema);
|
||||
let code = if content.is_empty() { " " } else { content };
|
||||
// A language this build cannot parse, or code that does not parse yet, keeps the
|
||||
// schema the draft had.
|
||||
let schema = infer_script_schema(language, code, Some(&previous), None).unwrap_or(previous);
|
||||
draft.insert("schema".into(), schema);
|
||||
// parse keeps the schema as it was. The chat infers with the editor's own parsers
|
||||
// before saving, so its schema matches what the editor shows.
|
||||
if ctx.surface == Surface::Mcp {
|
||||
let previous = draft
|
||||
.get("schema")
|
||||
.filter(|schema| truthy(schema.get("properties")))
|
||||
.cloned()
|
||||
.unwrap_or_else(empty_schema);
|
||||
let code = if content.is_empty() { " " } else { content };
|
||||
// A language this build cannot parse, or code that does not parse yet, keeps
|
||||
// the schema the draft had.
|
||||
let schema = infer_script_schema(language, code, Some(&previous), None).unwrap_or(previous);
|
||||
draft.insert("schema".into(), schema);
|
||||
}
|
||||
ctx.code_diff(&before, content, Some(language));
|
||||
let persisted = persist_draft(
|
||||
ctx,
|
||||
"script",
|
||||
@@ -1755,7 +1915,11 @@ async fn discard_local_draft(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
let not_found = || format!("No draft found for {item_type} \"{path}\".");
|
||||
let kind = draft_kind(item_type, trigger_kind).ok_or_else(not_found)?;
|
||||
let draft = get_draft(ctx, &kind, path).await?.ok_or_else(not_found)?;
|
||||
delete_draft(ctx, &kind, path, draft.created_at.as_deref()).await?;
|
||||
delete_draft(ctx, &kind, path, draft.created_at.as_deref(), false).await?;
|
||||
ctx.status_after_save(
|
||||
format!("Discarded {item_type} \"{path}\" draft"),
|
||||
Some("Draft discarded"),
|
||||
);
|
||||
let mut out = Map::new();
|
||||
out.insert("success".into(), json!(true));
|
||||
out.insert(
|
||||
@@ -1826,18 +1990,18 @@ async fn rebase_draft(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
.as_ref()
|
||||
.map_or_else(|| "undefined".to_string(), js_str);
|
||||
if base.is_some() && base == head {
|
||||
let message = format!(
|
||||
"Draft \"{path}\" is already based on the latest deployed version ({head_text})."
|
||||
);
|
||||
ctx.status(message.clone());
|
||||
let mut out = Map::new();
|
||||
out.insert("success".into(), json!(true));
|
||||
out.insert("alreadyLatest".into(), json!(true));
|
||||
put(&mut out, head_key, head);
|
||||
out.insert(
|
||||
"message".into(),
|
||||
json!(format!(
|
||||
"Draft \"{path}\" is already based on the latest deployed version ({head_text})."
|
||||
)),
|
||||
);
|
||||
out.insert("message".into(), json!(message));
|
||||
return Ok(Value::Object(out).to_string());
|
||||
}
|
||||
ctx.status(format!("Rebasing draft \"{path}\" onto latest..."));
|
||||
|
||||
// Captured before the discard: this diff is the only record of what to replay. A
|
||||
// base version that can no longer be fetched diffs against nothing, so the whole
|
||||
@@ -1928,7 +2092,7 @@ async fn rebase_draft(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
let result = pretty(&Value::Object(out));
|
||||
// The diff is the only copy of the draft once it is discarded: a result the server
|
||||
// would truncate must keep the draft instead.
|
||||
if result.len() > windmill_mcp::server::MAX_TOOL_RESULT_BYTES {
|
||||
if ctx.surface == Surface::Mcp && result.len() > super::MAX_TOOL_RESULT_BYTES {
|
||||
let editor = match item_type {
|
||||
"script" => "/scripts/edit",
|
||||
"flow" => "/flows/edit",
|
||||
@@ -1940,7 +2104,8 @@ async fn rebase_draft(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
));
|
||||
}
|
||||
let kind = draft_kind(item_type, None).ok_or_else(no_draft)?;
|
||||
delete_draft(ctx, &kind, path, draft.created_at.as_deref()).await?;
|
||||
delete_draft(ctx, &kind, path, draft.created_at.as_deref(), false).await?;
|
||||
ctx.status_after_save(format!("Discarded stale draft \"{path}\""), Some("Rebased"));
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
@@ -40,8 +40,11 @@ use crate::triggers::trigger_helpers::RunnableId;
|
||||
pub struct CrossSiteGetGuard(Option<CrossSite>);
|
||||
|
||||
impl CrossSiteGetGuard {
|
||||
pub fn script_runnable(&self, script_path: &str) -> windmill_common::error::Result<RunnableId> {
|
||||
let runnable_id = RunnableId::from_script_path(script_path);
|
||||
pub fn script_runnable(
|
||||
&self,
|
||||
script: &windmill_common::runnable_ref::RunnableRef,
|
||||
) -> windmill_common::error::Result<RunnableId> {
|
||||
let runnable_id = RunnableId::from_script_path(script.path());
|
||||
let (Some(signal), RunnableId::HubScript(_)) = (&self.0, &runnable_id) else {
|
||||
return Ok(runnable_id);
|
||||
};
|
||||
|
||||
@@ -121,6 +121,7 @@ use windmill_common::{
|
||||
},
|
||||
oauth2::HmacSha256,
|
||||
query_builders,
|
||||
runnable_ref::RunnableRef,
|
||||
scripts::{ScriptHash, ScriptLang},
|
||||
users::username_to_permissioned_as,
|
||||
utils::{
|
||||
@@ -297,6 +298,10 @@ pub fn workspaced_service() -> Router {
|
||||
.route("/run/dynamic_select", post(run_dynamic_select))
|
||||
.route("/list", get(list_jobs))
|
||||
.route("/oldest", get(get_oldest_job))
|
||||
.route(
|
||||
"/recent_runs",
|
||||
get(crate::jobs_recent_runs::list_recent_runs),
|
||||
)
|
||||
.route("/asset_dispatch_edges", get(list_asset_dispatch_edges))
|
||||
.route(
|
||||
"/list_selected_job_groups",
|
||||
@@ -7185,10 +7190,11 @@ pub async fn run_flow_by_path(
|
||||
Query(run_query): Query<RunJobQuery>,
|
||||
args: RawWebhookArgs,
|
||||
) -> error::Result<(StatusCode, String)> {
|
||||
let flow = RunnableRef::from_path(&flow_path.0, true)?;
|
||||
let (args, trigger_metadata) = match get_args_and_trigger_metadata(
|
||||
&db,
|
||||
&authed,
|
||||
RunnableId::from_flow_path(flow_path.to_path()),
|
||||
RunnableId::from_flow_path(flow.path()),
|
||||
&run_query,
|
||||
&w_id,
|
||||
args,
|
||||
@@ -7209,7 +7215,7 @@ pub async fn run_flow_by_path(
|
||||
None,
|
||||
user_db,
|
||||
w_id,
|
||||
flow_path,
|
||||
StripPath(flow.path().to_string()),
|
||||
run_query,
|
||||
args,
|
||||
trigger_metadata,
|
||||
@@ -7638,10 +7644,11 @@ pub async fn run_script_by_path(
|
||||
Query(run_query): Query<RunJobQuery>,
|
||||
args: RawWebhookArgs,
|
||||
) -> error::Result<(StatusCode, String)> {
|
||||
let script = RunnableRef::from_path(&script_path.0, false)?;
|
||||
let (args, trigger_metadata) = match get_args_and_trigger_metadata(
|
||||
&db,
|
||||
&authed,
|
||||
RunnableId::from_script_path(script_path.to_path()),
|
||||
RunnableId::from_script_path(script.path()),
|
||||
&run_query,
|
||||
&w_id,
|
||||
args,
|
||||
@@ -7660,7 +7667,7 @@ pub async fn run_script_by_path(
|
||||
None,
|
||||
user_db,
|
||||
w_id,
|
||||
script_path,
|
||||
StripPath(script.path().to_string()),
|
||||
run_query,
|
||||
args,
|
||||
trigger_metadata,
|
||||
@@ -8178,8 +8185,9 @@ pub async fn run_wait_result_job_by_path_get(
|
||||
#[cfg(feature = "enterprise")]
|
||||
check_license_key_valid().await?;
|
||||
|
||||
let script_path = script_path.to_path();
|
||||
let runnable_id = cross_site.script_runnable(script_path)?;
|
||||
let script = RunnableRef::from_path(&script_path.0, false)?;
|
||||
let script_path = script.path();
|
||||
let runnable_id = cross_site.script_runnable(&script)?;
|
||||
check_scopes(&authed, || format!("jobs:run:scripts:{script_path}"))?;
|
||||
|
||||
if method == http::Method::HEAD {
|
||||
@@ -8286,7 +8294,8 @@ pub async fn run_wait_result_flow_by_path_get(
|
||||
#[cfg(feature = "enterprise")]
|
||||
check_license_key_valid().await?;
|
||||
|
||||
let path = flow_path.to_path();
|
||||
let flow = RunnableRef::from_path(&flow_path.0, true)?;
|
||||
let path = flow.path();
|
||||
check_scopes(&authed, || format!("jobs:run:flows:{path}"))?;
|
||||
|
||||
if method == http::Method::HEAD {
|
||||
@@ -8306,8 +8315,7 @@ pub async fn run_wait_result_flow_by_path_get(
|
||||
)
|
||||
.await?;
|
||||
|
||||
run_wait_result_flow_by_path_internal(db, run_query, flow_path, authed, user_db, args, w_id)
|
||||
.await
|
||||
run_wait_result_flow_by_path_internal(db, run_query, &flow, authed, user_db, args, w_id).await
|
||||
}
|
||||
|
||||
pub async fn run_wait_result_script_by_path(
|
||||
@@ -8321,7 +8329,8 @@ pub async fn run_wait_result_script_by_path(
|
||||
#[cfg(feature = "enterprise")]
|
||||
check_license_key_valid().await?;
|
||||
|
||||
let path = script_path.to_path();
|
||||
let script = RunnableRef::from_path(&script_path.0, false)?;
|
||||
let path = script.path();
|
||||
check_scopes(&authed, || format!("jobs:run:scripts:{path}"))?;
|
||||
|
||||
let args = args
|
||||
@@ -8334,14 +8343,14 @@ pub async fn run_wait_result_script_by_path(
|
||||
)
|
||||
.await?;
|
||||
|
||||
run_wait_result_script_by_path_internal(db, run_query, script_path, authed, user_db, w_id, args)
|
||||
run_wait_result_script_by_path_internal(db, run_query, &script, authed, user_db, w_id, args)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn run_wait_result_script_by_path_internal(
|
||||
db: sqlx::Pool<Postgres>,
|
||||
run_query: RunJobQuery,
|
||||
script_path: StripPath,
|
||||
script: &RunnableRef,
|
||||
authed: ApiAuthed,
|
||||
user_db: UserDB,
|
||||
w_id: String,
|
||||
@@ -8352,7 +8361,7 @@ pub async fn run_wait_result_script_by_path_internal(
|
||||
let db_authed = UserDbWithAuthed { db: user_db.clone(), authed: &authed.to_authed_ref() };
|
||||
let (job_payload, tag, delete_after_use, delete_after_secs, timeout, on_behalf_of) =
|
||||
script_path_to_payload(
|
||||
script_path.to_path(),
|
||||
script.path(),
|
||||
Some(db_authed),
|
||||
db.clone(),
|
||||
&w_id,
|
||||
@@ -8569,7 +8578,8 @@ pub async fn run_wait_result_flow_by_path(
|
||||
#[cfg(feature = "enterprise")]
|
||||
check_license_key_valid().await?;
|
||||
|
||||
let path = flow_path.to_path();
|
||||
let flow = RunnableRef::from_path(&flow_path.0, true)?;
|
||||
let path = flow.path();
|
||||
check_scopes(&authed, || format!("jobs:run:flows:{path}"))?;
|
||||
|
||||
let args = args
|
||||
@@ -8582,8 +8592,7 @@ pub async fn run_wait_result_flow_by_path(
|
||||
)
|
||||
.await?;
|
||||
|
||||
run_wait_result_flow_by_path_internal(db, run_query, flow_path, authed, user_db, args, w_id)
|
||||
.await
|
||||
run_wait_result_flow_by_path_internal(db, run_query, &flow, authed, user_db, args, w_id).await
|
||||
}
|
||||
|
||||
pub async fn stream_flow_by_path(
|
||||
@@ -8600,7 +8609,7 @@ pub async fn stream_flow_by_path(
|
||||
db,
|
||||
user_db,
|
||||
w_id,
|
||||
RunnableId::from_flow_path(flow_path.to_path()),
|
||||
RunnableId::from_flow_path(RunnableRef::from_path(&flow_path.0, true)?.path()),
|
||||
args,
|
||||
run_query,
|
||||
method == http::Method::GET,
|
||||
@@ -8640,7 +8649,8 @@ pub async fn stream_script_by_path(
|
||||
method: hyper::http::Method,
|
||||
args: RawWebhookArgs,
|
||||
) -> error::Result<Response> {
|
||||
let runnable_id = cross_site.script_runnable(script_path.to_path())?;
|
||||
let runnable_id =
|
||||
cross_site.script_runnable(&RunnableRef::from_path(&script_path.0, false)?)?;
|
||||
stream_job(
|
||||
authed,
|
||||
db,
|
||||
@@ -8821,7 +8831,7 @@ pub async fn stream_job(
|
||||
pub async fn run_wait_result_flow_by_path_internal(
|
||||
db: sqlx::Pool<Postgres>,
|
||||
run_query: RunJobQuery,
|
||||
flow_path: StripPath,
|
||||
flow: &RunnableRef,
|
||||
authed: ApiAuthed,
|
||||
user_db: UserDB,
|
||||
args: PushArgsOwned,
|
||||
@@ -8829,7 +8839,7 @@ pub async fn run_wait_result_flow_by_path_internal(
|
||||
) -> error::Result<Response> {
|
||||
check_queue_too_long(&db, run_query.queue_limit).await?;
|
||||
|
||||
let flow_path = flow_path.to_path();
|
||||
let flow_path = flow.path();
|
||||
|
||||
let userdb_authed = UserDbWithAuthed { db: user_db.clone(), authed: &authed.to_authed_ref() };
|
||||
|
||||
@@ -9344,15 +9354,15 @@ async fn run_inline_script_by_path(
|
||||
Path((w_id, script_path)): Path<(String, StripPath)>,
|
||||
Json(body): Json<InlineScriptArgs>,
|
||||
) -> error::Result<Response> {
|
||||
let script_path_str = script_path.to_path();
|
||||
check_scopes(&authed, || format!("jobs:run:scripts:{script_path_str}"))?;
|
||||
let script = RunnableRef::from_path(&script_path.0, false)?;
|
||||
check_scopes(&authed, || format!("jobs:run:scripts:{}", script.path()))?;
|
||||
run_inline_script_inner(
|
||||
authed,
|
||||
token,
|
||||
db,
|
||||
w_id,
|
||||
// Resolved to a version by `run_inline_script_inner`.
|
||||
InlineScriptTarget::Path { path: script_path.to_path().to_string(), hash: 0 },
|
||||
InlineScriptTarget::Path { path: script.path().to_string(), hash: 0 },
|
||||
body.args,
|
||||
Some(user_db),
|
||||
)
|
||||
@@ -10082,6 +10092,7 @@ async fn add_batch_jobs(
|
||||
) = match batch_info.kind.as_str() {
|
||||
"script" => {
|
||||
if let Some(path) = batch_info.path {
|
||||
let path = RunnableRef::from_path(&path, false)?.path().to_string();
|
||||
let db_authed =
|
||||
UserDbWithAuthed { db: user_db.clone(), authed: &authed.to_authed_ref() };
|
||||
let ScriptHashInfo {
|
||||
@@ -10141,6 +10152,7 @@ async fn add_batch_jobs(
|
||||
let (mut value, job_kind, path) = if let Some(value) = batch_info.flow_value {
|
||||
(value, JobKind::FlowPreview, None)
|
||||
} else if let Some(path) = batch_info.path {
|
||||
let path = RunnableRef::from_path(&path, true)?.path().to_string();
|
||||
let mut tx = user_db.clone().begin(&authed).await?;
|
||||
let value_json = sqlx::query!(
|
||||
"SELECT coalesce(flow_version_lite.value, flow_version.value) as \"value!: sqlx::types::Json<Box<RawValue>>\", flow.job_token_scopes FROM flow
|
||||
@@ -10565,7 +10577,7 @@ async fn run_dynamic_select(
|
||||
None,
|
||||
user_db.clone(),
|
||||
w_id.clone(),
|
||||
StripPath(path),
|
||||
StripPath(RunnableRef::from_path(&path, false)?.path().to_string()),
|
||||
run_query.clone(),
|
||||
push_args,
|
||||
None,
|
||||
@@ -10577,6 +10589,7 @@ async fn run_dynamic_select(
|
||||
RunnableKind::Flow => {
|
||||
// Runs the deployed flow's dynamic-select code. Path-scoped so a token not
|
||||
// scoped to this flow cannot trigger its code through dynamic select.
|
||||
let path = RunnableRef::from_path(&path, true)?.path().to_string();
|
||||
check_scopes(&authed, || format!("jobs:run:flows:{path}"))?;
|
||||
let mut conn = user_db.clone().begin(&authed).await?;
|
||||
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
//! What ran recently in a workspace, one entry per runnable: the workspace home's "Recently run"
|
||||
//! panel. Statuses and counts are settled here so the page only displays them.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use axum::{
|
||||
extract::{Path, Query},
|
||||
Extension, Json,
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use windmill_common::{db::UserDB, error::JsonResult};
|
||||
|
||||
use crate::{db::ApiAuthed, users::get_scope_tags};
|
||||
|
||||
const WINDOW_HOURS: i32 = 24;
|
||||
/// Newest root runs read from the window. A workspace running more than this in the window
|
||||
/// gets counts over these runs only, and `capped` says so.
|
||||
const SCAN_LIMIT: i64 = 5000;
|
||||
/// Newest completions examined, flow steps included, to find those root runs. Each costs a
|
||||
/// `v2_job` lookup, so this bounds a read where steps outnumber root runs; the counts then cover
|
||||
/// a shorter span than the window, and `capped` says so.
|
||||
const EXAMINE_LIMIT: i64 = 50_000;
|
||||
const MAX_ITEMS: usize = 50;
|
||||
const RUNS_PER_ITEM: usize = 10;
|
||||
|
||||
/// The root runs the panel lists, on `j` (`v2_job`). An agent's run is filed under the agent's
|
||||
/// path as a raw flow; an editor's flow preview also carries a path, so only a raw flow whose
|
||||
/// path names a saved agent counts.
|
||||
const LISTED_ROOT_RUN: &str = "j.workspace_id = $1
|
||||
AND j.parent_job IS NULL
|
||||
AND j.runnable_path IS NOT NULL
|
||||
AND ($3::text IS NULL OR starts_with(j.runnable_path, $3))
|
||||
AND ($5::text[] IS NULL OR j.tag = ANY($5))
|
||||
AND (j.kind IN ('script', 'singlestepflow', 'flow')
|
||||
OR (j.kind = 'flowpreview' AND EXISTS (
|
||||
SELECT 1 FROM resource res
|
||||
WHERE res.workspace_id = j.workspace_id AND res.path = j.runnable_path
|
||||
AND res.resource_type = 'ai_agent')))";
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct RecentRunsQuery {
|
||||
folder: Option<String>,
|
||||
/// With `failed_ids_path`: list that item's unresolved failures in `failed_run_ids`. Only on
|
||||
/// request, since a constantly failing item would put thousands of ids in every poll.
|
||||
failed_ids_kind: Option<String>,
|
||||
failed_ids_path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct RecentRuns {
|
||||
window_hours: i32,
|
||||
capped: bool,
|
||||
total_runs: i64,
|
||||
failed_runs: i64,
|
||||
failing_items: i64,
|
||||
running_items: i64,
|
||||
items: Vec<RecentRunItem>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct RecentRunItem {
|
||||
path: String,
|
||||
kind: String,
|
||||
summary: Option<String>,
|
||||
/// The status of the item's newest run.
|
||||
status: String,
|
||||
/// Unresolved failures over the whole window, not only the runs listed.
|
||||
failed_runs: i64,
|
||||
/// Their ids, for the item named by the query's `failed_ids_*` only.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
failed_run_ids: Option<Vec<uuid::Uuid>>,
|
||||
/// Newest first.
|
||||
runs: Vec<RecentRun>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, sqlx::FromRow)]
|
||||
pub(crate) struct RecentRun {
|
||||
id: uuid::Uuid,
|
||||
#[serde(skip)]
|
||||
path: String,
|
||||
#[serde(skip)]
|
||||
kind: String,
|
||||
status: String,
|
||||
/// When the run started, or was created for one that has not reported a start.
|
||||
ran_at: DateTime<Utc>,
|
||||
duration_ms: Option<i64>,
|
||||
#[serde(skip)]
|
||||
examine_capped: bool,
|
||||
}
|
||||
|
||||
pub(crate) async fn list_recent_runs(
|
||||
authed: ApiAuthed,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Path(w_id): Path<String>,
|
||||
Query(q): Query<RecentRunsQuery>,
|
||||
) -> JsonResult<RecentRuns> {
|
||||
let folder = q
|
||||
.folder
|
||||
.filter(|f| !f.is_empty())
|
||||
.map(|f| format!("f/{f}/"));
|
||||
let failed_ids_of = q.failed_ids_kind.zip(q.failed_ids_path);
|
||||
let mut tx = user_db.begin(&authed).await?;
|
||||
|
||||
// A run counts when it completed in the window or is running now, whenever it was queued:
|
||||
// a schedule is queued a full period ahead of its run. The completed side walks the
|
||||
// (workspace_id, completed_at) index newest first, no further back than the EXAMINE_LIMIT-th
|
||||
// completion (`since`, read index-only). Its root check is a per-row `v2_job` lookup:
|
||||
// `OFFSET 0` keeps the planner from turning it into a join over every root run the
|
||||
// workspace ever had, which grows with its history rather than with the window.
|
||||
// A `singlestepflow` wraps a script or a flow.
|
||||
let scope_tags =
|
||||
get_scope_tags(&authed).map(|v| v.into_iter().map(str::to_string).collect::<Vec<_>>());
|
||||
let runs = sqlx::query_as::<_, RecentRun>(&format!(
|
||||
"WITH bound AS (
|
||||
SELECT (SELECT c.completed_at FROM v2_job_completed c
|
||||
WHERE c.workspace_id = $1
|
||||
AND c.completed_at > now() - make_interval(hours => $2)
|
||||
ORDER BY c.completed_at DESC
|
||||
OFFSET $6 - 1 LIMIT 1) AS since
|
||||
), ran AS (
|
||||
(SELECT c.id, c.status::text AS status, c.started_at,
|
||||
c.duration_ms::bigint AS duration_ms, c.completed_at
|
||||
FROM v2_job_completed c
|
||||
CROSS JOIN LATERAL (SELECT FROM v2_job j
|
||||
WHERE j.id = c.id AND {LISTED_ROOT_RUN} OFFSET 0) root
|
||||
WHERE c.workspace_id = $1 AND c.completed_at > now() - make_interval(hours => $2)
|
||||
AND c.completed_at >= COALESCE((SELECT since FROM bound), '-infinity')
|
||||
ORDER BY c.completed_at DESC
|
||||
LIMIT $4)
|
||||
UNION ALL
|
||||
(SELECT q.id, NULL, q.started_at, NULL, NULL
|
||||
FROM v2_job_queue q
|
||||
JOIN v2_job j ON j.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))
|
||||
)
|
||||
SELECT j.id, j.runnable_path AS path,
|
||||
CASE WHEN j.kind = 'flow' THEN 'flow'
|
||||
WHEN j.kind = 'flowpreview' THEN 'agent'
|
||||
WHEN j.kind = 'singlestepflow' AND COALESCE(
|
||||
(SELECT m->'value'->>'type'
|
||||
FROM jsonb_array_elements(j.raw_flow->'modules') m
|
||||
WHERE m->>'id' IN ('a', 'main')
|
||||
LIMIT 1),
|
||||
'script') = 'flow' THEN 'flow'
|
||||
ELSE 'script' END AS kind,
|
||||
CASE WHEN r.status IS NULL THEN 'running'
|
||||
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'
|
||||
ELSE 'failure' END AS status,
|
||||
COALESCE(r.started_at, j.created_at) AS ran_at,
|
||||
r.duration_ms,
|
||||
(SELECT since FROM bound) IS NOT NULL AS examine_capped
|
||||
FROM ran r
|
||||
JOIN v2_job j ON j.id = r.id
|
||||
ORDER BY r.completed_at DESC NULLS FIRST, ran_at DESC
|
||||
LIMIT $4"
|
||||
))
|
||||
.bind(&w_id)
|
||||
.bind(WINDOW_HOURS)
|
||||
.bind(&folder)
|
||||
.bind(SCAN_LIMIT)
|
||||
.bind(&scope_tags)
|
||||
.bind(EXAMINE_LIMIT)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?;
|
||||
|
||||
let capped = runs.len() as i64 == SCAN_LIMIT || runs.first().is_some_and(|r| r.examine_capped);
|
||||
let total_runs = runs.len() as i64;
|
||||
let failed_runs = runs.iter().filter(|r| r.status == "failure").count() as i64;
|
||||
|
||||
// A script and a flow can share a path: they are two items.
|
||||
let mut items: Vec<RecentRunItem> = vec![];
|
||||
let mut index: HashMap<(String, String), usize> = HashMap::new();
|
||||
for run in runs {
|
||||
let failed = run.status == "failure";
|
||||
let wanted = failed_ids_of
|
||||
.as_ref()
|
||||
.is_some_and(|(k, p)| *k == run.kind && *p == run.path);
|
||||
match index.get(&(run.kind.clone(), run.path.clone())) {
|
||||
Some(&i) => {
|
||||
items[i].failed_runs += failed as i64;
|
||||
if failed && wanted {
|
||||
items[i].failed_run_ids.get_or_insert_with(Vec::new).push(run.id);
|
||||
}
|
||||
if items[i].runs.len() < RUNS_PER_ITEM {
|
||||
items[i].runs.push(run);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
index.insert((run.kind.clone(), run.path.clone()), items.len());
|
||||
items.push(RecentRunItem {
|
||||
path: run.path.clone(),
|
||||
kind: run.kind.clone(),
|
||||
summary: None,
|
||||
status: run.status.clone(),
|
||||
failed_runs: failed as i64,
|
||||
failed_run_ids: wanted.then(|| if failed { vec![run.id] } else { vec![] }),
|
||||
runs: vec![run],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let failing_items = items.iter().filter(|i| i.status == "failure").count() as i64;
|
||||
let running_items = items.iter().filter(|i| i.status == "running").count() as i64;
|
||||
items.truncate(MAX_ITEMS);
|
||||
|
||||
let kinds: Vec<String> = items.iter().map(|i| i.kind.clone()).collect();
|
||||
let paths: Vec<String> = items.iter().map(|i| i.path.clone()).collect();
|
||||
let summaries: HashMap<(String, String), String> =
|
||||
sqlx::query_as::<_, (String, String, Option<String>)>(
|
||||
"SELECT p.kind, p.path, CASE p.kind
|
||||
WHEN 'script' THEN (SELECT NULLIF(s.summary, '') FROM script s
|
||||
WHERE s.workspace_id = $1 AND s.path = p.path AND NOT s.archived
|
||||
ORDER BY s.created_at DESC LIMIT 1)
|
||||
WHEN 'flow' THEN (SELECT NULLIF(f.summary, '') FROM flow f
|
||||
WHERE f.workspace_id = $1 AND f.path = p.path)
|
||||
ELSE (SELECT NULLIF(r.description, '') FROM resource r
|
||||
WHERE r.workspace_id = $1 AND r.path = p.path AND r.resource_type = 'ai_agent')
|
||||
END
|
||||
FROM unnest($2::text[], $3::text[]) AS p(kind, path)",
|
||||
)
|
||||
.bind(&w_id)
|
||||
.bind(&kinds)
|
||||
.bind(&paths)
|
||||
.fetch_all(&mut *tx)
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter_map(|(k, p, s)| s.map(|s| ((k, p), s)))
|
||||
.collect();
|
||||
tx.commit().await?;
|
||||
|
||||
for item in items.iter_mut() {
|
||||
item.summary = summaries
|
||||
.get(&(item.kind.clone(), item.path.clone()))
|
||||
.cloned();
|
||||
}
|
||||
|
||||
Ok(Json(RecentRuns {
|
||||
window_hours: WINDOW_HOURS,
|
||||
capped,
|
||||
total_runs,
|
||||
failed_runs,
|
||||
failing_items,
|
||||
running_items,
|
||||
items,
|
||||
}))
|
||||
}
|
||||
@@ -141,6 +141,7 @@ mod job_helpers_oss;
|
||||
pub mod job_metrics;
|
||||
pub mod jobs;
|
||||
pub mod jobs_export;
|
||||
mod jobs_recent_runs;
|
||||
#[cfg(all(feature = "oauth2", feature = "private"))]
|
||||
pub mod oauth2_ee;
|
||||
#[cfg(feature = "oauth2")]
|
||||
@@ -159,6 +160,7 @@ mod saml_oss;
|
||||
#[cfg(feature = "private")]
|
||||
pub mod scim_ee;
|
||||
mod scim_oss;
|
||||
mod session_hint;
|
||||
mod scripts;
|
||||
mod secret_backend_ext;
|
||||
mod service_logs;
|
||||
@@ -207,12 +209,13 @@ mod variables;
|
||||
pub mod volumes_ee;
|
||||
mod volumes_oss;
|
||||
pub mod webhook_util;
|
||||
mod workspace_settings_document;
|
||||
mod workspaces;
|
||||
#[cfg(feature = "private")]
|
||||
pub mod workspaces_ee;
|
||||
mod workspaces_export;
|
||||
mod workspace_settings_document;
|
||||
|
||||
mod ai_session_tools;
|
||||
#[cfg(feature = "mcp")]
|
||||
mod mcp_tools;
|
||||
|
||||
@@ -448,6 +451,7 @@ pub async fn run_server(
|
||||
.layer(Extension(job_index_reader))
|
||||
.layer(Extension(log_index_reader))
|
||||
// .layer(Extension(index_writer))
|
||||
.layer(axum::middleware::from_fn(session_hint::mirror_session_cookie))
|
||||
.layer(CookieManagerLayer::new())
|
||||
.layer(Extension(WebhookShared::new(
|
||||
killpill_rx.resubscribe(),
|
||||
@@ -780,6 +784,10 @@ pub async fn run_server(
|
||||
Router::new()
|
||||
})
|
||||
.nest("/ai", ai::workspaced_service())
|
||||
.nest(
|
||||
"/ai_session_tools",
|
||||
ai_session_tools::chat::workspaced_service(_base_internal_url.clone()),
|
||||
)
|
||||
.nest("/npm_proxy", windmill_api_npm_proxy::workspaced_service())
|
||||
.nest(
|
||||
"/path_autocomplete",
|
||||
@@ -1287,8 +1295,7 @@ pub async fn run_server(
|
||||
if let Some(name) = name.as_ref() {
|
||||
tracing::info!("server starting for name={name}");
|
||||
}
|
||||
#[cfg(feature = "mcp")]
|
||||
mcp::register_router(&_base_internal_url, Some(app.clone()));
|
||||
ai_session_tools::register_router(&_base_internal_url, Some(app.clone()));
|
||||
|
||||
let listener = listener.tap_io(move |tcp_stream| {
|
||||
let _ = tcp_stream.set_nodelay(!server_mode);
|
||||
@@ -1328,8 +1335,7 @@ pub async fn run_server(
|
||||
});
|
||||
|
||||
let served = server.await;
|
||||
#[cfg(feature = "mcp")]
|
||||
mcp::register_router(&_base_internal_url, None);
|
||||
ai_session_tools::register_router(&_base_internal_url, None);
|
||||
served?;
|
||||
let forks = &windmill_api_workspaces::workspaces::BACKGROUND_FORKS;
|
||||
forks.close();
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
use async_trait::async_trait;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use windmill_common::{db::UserDB, utils::StripPath, DB};
|
||||
use windmill_common::{db::UserDB, runnable_ref::RunnableRef, DB};
|
||||
use windmill_mcp::common::schema::enrich_resource_schemas;
|
||||
use windmill_mcp::common::transform::transform_property_keys;
|
||||
use windmill_mcp::common::types::{
|
||||
@@ -83,15 +83,7 @@ impl WindmillBackend {
|
||||
w_id: &'a str,
|
||||
access: SessionAccess,
|
||||
) -> session::Ctx<'a> {
|
||||
session::Ctx {
|
||||
auth,
|
||||
w_id,
|
||||
base_internal_url: &self.base_internal_url,
|
||||
access,
|
||||
origin: None,
|
||||
jwt: Default::default(),
|
||||
view: Default::default(),
|
||||
}
|
||||
session::Ctx::new(auth, w_id, &self.base_internal_url, session::access(access))
|
||||
}
|
||||
|
||||
pub fn new(
|
||||
@@ -283,14 +275,16 @@ impl McpBackend for WindmillBackend {
|
||||
request: &McpRequest<'_>,
|
||||
) -> BackendResult<Value> {
|
||||
windmill_common::feature_usage::log_feature_usage("mcp", "runnable_tool_call", "script");
|
||||
let push_args = prepare_push_args(&self.db, workspace_id, path, false, args, request)
|
||||
let script = RunnableRef::from_path(path, false)
|
||||
.map_err(|e| ErrorData::internal_error(e.to_string(), None))?;
|
||||
let push_args = prepare_push_args(&self.db, workspace_id, &script, args, request)
|
||||
.await
|
||||
.map_err(|e| ErrorData::internal_error(e.to_string(), None))?;
|
||||
|
||||
let result = run_wait_result_script_by_path_internal(
|
||||
self.db.clone(),
|
||||
RunJobQuery::default(),
|
||||
StripPath(path.to_string()),
|
||||
&script,
|
||||
auth.clone(),
|
||||
self.user_db.clone(),
|
||||
workspace_id.to_string(),
|
||||
@@ -311,14 +305,16 @@ impl McpBackend for WindmillBackend {
|
||||
request: &McpRequest<'_>,
|
||||
) -> BackendResult<Value> {
|
||||
windmill_common::feature_usage::log_feature_usage("mcp", "runnable_tool_call", "flow");
|
||||
let push_args = prepare_push_args(&self.db, workspace_id, path, true, args, request)
|
||||
let flow = RunnableRef::from_path(path, true)
|
||||
.map_err(|e| ErrorData::internal_error(e.to_string(), None))?;
|
||||
let push_args = prepare_push_args(&self.db, workspace_id, &flow, args, request)
|
||||
.await
|
||||
.map_err(|e| ErrorData::internal_error(e.to_string(), None))?;
|
||||
|
||||
let result = run_wait_result_flow_by_path_internal(
|
||||
self.db.clone(),
|
||||
RunJobQuery::default(),
|
||||
StripPath(path.to_string()),
|
||||
&flow,
|
||||
auth.clone(),
|
||||
self.user_db.clone(),
|
||||
push_args,
|
||||
@@ -503,7 +499,8 @@ impl McpBackend for WindmillBackend {
|
||||
access: SessionAccess,
|
||||
origin: Option<&str>,
|
||||
) -> BackendResult<CallToolResult> {
|
||||
let ctx = session::Ctx { origin, ..self.session_ctx_with(auth, workspace_id, access) };
|
||||
let mut ctx = self.session_ctx_with(auth, workspace_id, access);
|
||||
ctx.origin = origin;
|
||||
session::call_session_tool(&ctx, name, args).await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,4 +16,3 @@ pub use core::{
|
||||
extract_and_store_workspace_id, extract_workspace_from_token, list_tools_service,
|
||||
reject_token_query_param, setup_mcp_server, toolset_service, McpEndpoint,
|
||||
};
|
||||
pub(crate) use session::register_router;
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
//! The AI session's toolset (`crate::ai_session_tools`) as MCP serves it.
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
use windmill_mcp::server::{
|
||||
BackendResult, CallToolResult, ContentBlock, ErrorData, MetaObject, SessionAccess, Tool,
|
||||
ToolAnnotations,
|
||||
};
|
||||
|
||||
use crate::ai_session_tools::{self as tools, CallRefused};
|
||||
|
||||
pub(super) use tools::{
|
||||
generic_session_instructions, session_instructions, workspace_context, Ctx,
|
||||
};
|
||||
|
||||
pub(super) fn access(access: SessionAccess) -> tools::SessionAccess {
|
||||
match access {
|
||||
SessionAccess::ReadOnly => tools::SessionAccess::ReadOnly,
|
||||
SessionAccess::ReadAndRun => tools::SessionAccess::ReadAndRun,
|
||||
SessionAccess::Full => tools::SessionAccess::Full,
|
||||
}
|
||||
}
|
||||
|
||||
/// Claude clients keep an MCP result in context only up to a token budget well under the
|
||||
/// authoring references `get_instructions` returns, unless the tool raises it. Above the
|
||||
/// runner's own cap on a result, so that cap is the one that applies.
|
||||
fn result_size_meta() -> MetaObject {
|
||||
let mut meta = Map::new();
|
||||
meta.insert("anthropic/maxResultSizeChars".to_string(), 100_000.into());
|
||||
MetaObject(meta)
|
||||
}
|
||||
|
||||
/// The destructive tools a card may call, each from a button the user presses. Every
|
||||
/// other destructive tool is hidden from cards: a card acts as the user with no one
|
||||
/// confirming.
|
||||
const CARD_ACTIONS: &[&str] = &["deploy_workspace_item", "cancel_job"];
|
||||
|
||||
/// A tool's display name, which Claude shows in its tool list and approval prompts.
|
||||
fn tool_title(name: &str) -> String {
|
||||
let words: Vec<String> = name
|
||||
.split('_')
|
||||
.map(|word| match word {
|
||||
"db" | "sql" | "json" => word.to_uppercase(),
|
||||
_ => word.to_string(),
|
||||
})
|
||||
.collect();
|
||||
let title = words.join(" ");
|
||||
let mut chars = title.chars();
|
||||
chars
|
||||
.next()
|
||||
.map(|first| first.to_uppercase().chain(chars).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The MCP Apps view a client that renders them draws these tools' results in. It draws
|
||||
/// what the tool put in its result's `_meta` (`Ctx::view`), and acts by calling tools.
|
||||
/// Hosts cache a view by its URI: bump the version when a change breaks the `_meta` shape
|
||||
/// the deployed card reads.
|
||||
pub(super) const CARD_URI: &str = "ui://windmill/card-v1";
|
||||
const CARD_HTML: &str = include_str!("card.html");
|
||||
|
||||
/// The `ui://` views the session's tools render in, as `(uri, html)`.
|
||||
pub(super) fn session_views() -> &'static [(&'static str, &'static str)] {
|
||||
&[(CARD_URI, CARD_HTML)]
|
||||
}
|
||||
|
||||
pub(super) fn session_tools(session_access: SessionAccess) -> Vec<Tool> {
|
||||
let access = access(session_access);
|
||||
tools::session_tools(access)
|
||||
.map(|tool| {
|
||||
let mut meta = result_size_meta();
|
||||
if tool.destructive && !CARD_ACTIONS.contains(&tool.name) {
|
||||
meta.0
|
||||
.insert("ui".into(), json!({ "visibility": ["model"] }));
|
||||
}
|
||||
let title = tool_title(tool.name);
|
||||
Tool::new(tool.name, tool.description, tool.parameters.clone())
|
||||
.with_title(title.clone())
|
||||
.with_annotations(
|
||||
ToolAnnotations::with_title(title)
|
||||
.read_only(tool.read_only)
|
||||
.destructive(tool.destructive)
|
||||
.open_world(tool.open_world),
|
||||
)
|
||||
.with_meta(meta)
|
||||
})
|
||||
.chain(
|
||||
tools::view_definitions()
|
||||
.into_iter()
|
||||
.filter(|(name, ..)| tools::view_allowed(name, access))
|
||||
.map(|(name, description, schema)| {
|
||||
let mut meta = result_size_meta();
|
||||
meta.0
|
||||
.insert("ui".into(), json!({ "resourceUri": CARD_URI }));
|
||||
let Value::Object(schema) = schema else {
|
||||
unreachable!("a view tool's schema is an object")
|
||||
};
|
||||
let title = tool_title(name);
|
||||
Tool::new(name, description, schema)
|
||||
.with_title(title.clone())
|
||||
.with_annotations(
|
||||
ToolAnnotations::with_title(title)
|
||||
.read_only(true)
|
||||
.destructive(false)
|
||||
.open_world(false),
|
||||
)
|
||||
.with_meta(meta)
|
||||
}),
|
||||
)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) async fn call_session_tool(
|
||||
ctx: &Ctx<'_>,
|
||||
name: &str,
|
||||
args: Value,
|
||||
) -> BackendResult<CallToolResult> {
|
||||
let outcome =
|
||||
tools::call_session_tool(ctx, name, args)
|
||||
.await
|
||||
.map_err(|refused| match refused {
|
||||
CallRefused::NotAllowed(message) => ErrorData::invalid_request(message, None),
|
||||
CallRefused::UnknownTool(message) | CallRefused::NotAvailable(message) => {
|
||||
ErrorData::invalid_params(message, None)
|
||||
}
|
||||
})?;
|
||||
windmill_common::feature_usage::log_feature_usage("mcp_workspace", "tool_call", name);
|
||||
let content = vec![ContentBlock::text(outcome.text)];
|
||||
let mut result = if outcome.is_error {
|
||||
CallToolResult::error(content)
|
||||
} else {
|
||||
CallToolResult::success(content)
|
||||
};
|
||||
if let Some((key, view)) = ctx.view.lock().unwrap().take() {
|
||||
result.meta = Some(MetaObject(Map::from_iter([(key.to_string(), view)])));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn no_card_can_call_a_destructive_tool_but_deploy_and_cancel() {
|
||||
for tool in session_tools(SessionAccess::Full) {
|
||||
let name = tool.name.as_ref();
|
||||
let destructive = tool.annotations.as_ref().and_then(|a| a.destructive_hint);
|
||||
if destructive == Some(true) {
|
||||
let ui = tool.meta.as_ref().and_then(|m| m.0.get("ui"));
|
||||
let model_only = ui == Some(&json!({ "visibility": ["model"] }));
|
||||
assert_eq!(
|
||||
model_only,
|
||||
!matches!(name, "deploy_workspace_item" | "cancel_job"),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The ChatGPT directory wants every hint explicit, and Claude's a title on every tool.
|
||||
#[test]
|
||||
fn every_session_tool_has_a_title_and_explicit_hints() {
|
||||
for tool in session_tools(SessionAccess::Full) {
|
||||
let a = tool.annotations.as_ref().expect("annotations");
|
||||
assert!(tool.title.is_some() && a.title.is_some(), "{}", tool.name);
|
||||
assert!(
|
||||
a.read_only_hint.is_some()
|
||||
&& a.destructive_hint.is_some()
|
||||
&& a.open_world_hint.is_some(),
|
||||
"{}",
|
||||
tool.name
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,9 +9,9 @@ use axum::body::{to_bytes, Body};
|
||||
use axum::response::Response;
|
||||
use serde_json::Value;
|
||||
use sql_builder::prelude::*;
|
||||
use windmill_common::auth::create_jwt_token;
|
||||
use windmill_common::db::{Authed, UserDB};
|
||||
use windmill_common::db::UserDB;
|
||||
use windmill_common::error::Error;
|
||||
use windmill_common::runnable_ref::RunnableRef;
|
||||
use windmill_common::scripts::{get_full_hub_script_by_path, Schema};
|
||||
use windmill_common::triggers::{RunnableFormat, RunnableFormatVersion, TriggerKind};
|
||||
use windmill_common::utils::{query_elems_from_hub, StripPath};
|
||||
@@ -213,9 +213,7 @@ fn items_query(
|
||||
} else {
|
||||
let conds: Vec<String> = segments
|
||||
.iter()
|
||||
.map(|s| {
|
||||
"o.path LIKE ? ESCAPE '\\'".bind(&format!("%/{}", escape_like(s)))
|
||||
})
|
||||
.map(|s| "o.path LIKE ? ESCAPE '\\'".bind(&format!("%/{}", escape_like(s))))
|
||||
.collect();
|
||||
sqlb.and_where(format!("({})", conds.join(" OR ")));
|
||||
}
|
||||
@@ -710,28 +708,6 @@ pub async fn create_http_request(
|
||||
send_as_caller(method, url, workspace_id, api_authed, body_json, scopes).await
|
||||
}
|
||||
|
||||
/// A JWT that acts as `api_authed`, carrying `scopes`; `None` is the caller's full rights.
|
||||
pub(crate) async fn mint_caller_jwt(
|
||||
workspace_id: &str,
|
||||
api_authed: &ApiAuthed,
|
||||
scopes: Option<Vec<String>>,
|
||||
) -> BackendResult<String> {
|
||||
// Carry the caller's job provenance into the JWT: a job's WM_TOKEN is capped at
|
||||
// workspace admin (GHSA-hfh4-cx4h-3fcr), and dropping `job_id` here would re-mint an
|
||||
// uncapped token that satisfies require_super_admin / require_devops_role.
|
||||
create_jwt_token(
|
||||
Authed::from(api_authed.clone()),
|
||||
workspace_id,
|
||||
3600,
|
||||
api_authed.job_id,
|
||||
None,
|
||||
None,
|
||||
scopes,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| ErrorData::internal_error(e.to_string(), None))
|
||||
}
|
||||
|
||||
/// Call the API as `api_authed` with a JWT carrying `scopes`; `None` is the caller's
|
||||
/// full rights, for a server whose own code picks every route it calls.
|
||||
pub async fn send_as_caller(
|
||||
@@ -757,7 +733,9 @@ pub async fn send_as_caller(
|
||||
}
|
||||
};
|
||||
|
||||
let token = mint_caller_jwt(workspace_id, api_authed, scopes).await?;
|
||||
let token = crate::ai_session_tools::mint_caller_jwt(workspace_id, api_authed, scopes)
|
||||
.await
|
||||
.map_err(|e| ErrorData::internal_error(e.to_string(), None))?;
|
||||
request_builder = request_builder.header("Authorization", format!("Bearer {}", token));
|
||||
|
||||
// Add body if present
|
||||
@@ -815,8 +793,7 @@ fn preprocessor_headers(
|
||||
pub async fn prepare_push_args(
|
||||
db: &DB,
|
||||
w_id: &str,
|
||||
path: &str,
|
||||
is_flow: bool,
|
||||
runnable: &RunnableRef,
|
||||
args: Value,
|
||||
request: &McpRequest<'_>,
|
||||
) -> Result<windmill_queue::PushArgsOwned, Error> {
|
||||
@@ -827,11 +804,11 @@ pub async fn prepare_push_args(
|
||||
}
|
||||
}
|
||||
|
||||
let runnable_id = if is_flow {
|
||||
RunnableId::from_flow_path(path)
|
||||
let runnable_id = if runnable.is_flow() {
|
||||
RunnableId::from_flow_path(runnable.path())
|
||||
} else {
|
||||
// Resolves a `hub/<version_id>` path to the hub script on its own.
|
||||
RunnableId::from_script_path(path)
|
||||
RunnableId::from_script_path(runnable.path())
|
||||
};
|
||||
|
||||
// MCP is not one of the `TRIGGER_KIND` enum values and does not need to be:
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
//! A readable companion to the HttpOnly session cookie, so the frontend can tell whether the
|
||||
//! session it rendered for last is still the one the browser holds before `whoami` answers.
|
||||
//! It is derived from the token and cannot be turned back into it, so it grants nothing.
|
||||
//!
|
||||
//! Mirrored from the `Set-Cookie` headers rather than set beside each `token` cookie: every
|
||||
//! site that sets or clears the session, EE ones included, must move the hint with it, or the
|
||||
//! frontend would render one user's cached data under another's session.
|
||||
|
||||
use axum::{extract::Request, middleware::Next, response::Response};
|
||||
use http::{header::SET_COOKIE, HeaderValue};
|
||||
use sha2::{Digest, Sha256};
|
||||
use tower_cookies::Cookie;
|
||||
use windmill_common::users::COOKIE_NAME;
|
||||
|
||||
pub(crate) const SESSION_HINT_COOKIE: &str = "wm_session";
|
||||
|
||||
fn session_hint(token: &str) -> String {
|
||||
let digest = Sha256::new()
|
||||
.chain_update(b"windmill-session-hint\0")
|
||||
.chain_update(token.as_bytes())
|
||||
.finalize();
|
||||
hex::encode(&digest[..12])
|
||||
}
|
||||
|
||||
/// The hint cookie for a `token` cookie being set (or cleared, when its value is empty), with
|
||||
/// the same scope and lifetime.
|
||||
fn hint_for(session: &Cookie) -> Cookie<'static> {
|
||||
let value = if session.value().is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
session_hint(session.value())
|
||||
};
|
||||
let mut hint = Cookie::new(SESSION_HINT_COOKIE, value);
|
||||
if let Some(path) = session.path() {
|
||||
hint.set_path(path.to_string());
|
||||
}
|
||||
if let Some(domain) = session.domain() {
|
||||
hint.set_domain(domain.to_string());
|
||||
}
|
||||
if let Some(expires) = session.expires() {
|
||||
hint.set_expires(expires);
|
||||
}
|
||||
if let Some(max_age) = session.max_age() {
|
||||
hint.set_max_age(max_age);
|
||||
}
|
||||
if let Some(secure) = session.secure() {
|
||||
hint.set_secure(secure);
|
||||
}
|
||||
if let Some(same_site) = session.same_site() {
|
||||
hint.set_same_site(same_site);
|
||||
}
|
||||
hint.set_http_only(false);
|
||||
hint
|
||||
}
|
||||
|
||||
/// Must wrap `CookieManagerLayer`, which writes the `Set-Cookie` headers this reads.
|
||||
pub(crate) async fn mirror_session_cookie(req: Request, next: Next) -> Response {
|
||||
let mut res = next.run(req).await;
|
||||
let hints: Vec<HeaderValue> = res
|
||||
.headers()
|
||||
.get_all(SET_COOKIE)
|
||||
.iter()
|
||||
.filter_map(|v| v.to_str().ok())
|
||||
.filter_map(|s| Cookie::parse(s.to_owned()).ok())
|
||||
.filter(|c| c.name() == COOKIE_NAME)
|
||||
.filter_map(|c| HeaderValue::from_str(&hint_for(&c).to_string()).ok())
|
||||
.collect();
|
||||
for hint in hints {
|
||||
res.headers_mut().append(SET_COOKIE, hint);
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hint_follows_the_session_cookie_and_hides_the_token() {
|
||||
let set = Cookie::parse(
|
||||
"token=secret_token_value; Path=/; Domain=example.com; Secure; HttpOnly; \
|
||||
SameSite=Lax; Expires=Wed, 21 Oct 2037 07:28:00 GMT",
|
||||
)
|
||||
.unwrap();
|
||||
let hint = hint_for(&set);
|
||||
assert_eq!(hint.name(), SESSION_HINT_COOKIE);
|
||||
assert!(!hint.value().contains("secret_token_value"));
|
||||
assert_eq!(hint.value(), session_hint("secret_token_value"));
|
||||
assert_ne!(hint.value(), session_hint("another_token"));
|
||||
assert_eq!(hint.http_only(), Some(false));
|
||||
assert_eq!(hint.path(), Some("/"));
|
||||
assert_eq!(hint.domain(), Some("example.com"));
|
||||
assert_eq!(hint.expires(), set.expires());
|
||||
assert_eq!(hint.secure(), Some(true));
|
||||
|
||||
// A logout clears the session: the hint goes with it.
|
||||
let cleared = Cookie::parse("token=; Path=/; Max-Age=0").unwrap();
|
||||
let hint = hint_for(&cleared);
|
||||
assert_eq!(hint.value(), "");
|
||||
assert_eq!(hint.max_age(), cleared.max_age());
|
||||
}
|
||||
}
|
||||
@@ -85,7 +85,7 @@ pub async fn sync_metric_catalog(
|
||||
.execute(&mut *db)
|
||||
.await?;
|
||||
|
||||
let ann = parse_pipeline_annotations(content);
|
||||
let ann = parse_pipeline_annotations(content).for_script(script_path);
|
||||
let Some(spec) = ann
|
||||
.materialize
|
||||
.filter(|m| m.target_kind == AssetKind::Ducklake)
|
||||
|
||||
@@ -130,6 +130,7 @@ pub mod queue_metrics;
|
||||
pub mod result_stream;
|
||||
pub mod roles;
|
||||
pub mod runnable_job_stats;
|
||||
pub mod runnable_ref;
|
||||
pub mod runnable_settings;
|
||||
pub mod runnables;
|
||||
pub mod schedule;
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
//! The one parser for a script or flow named by path. A check and the resolution after it read
|
||||
//! this value, so they cannot disagree on what a string means. Save-time guards that only refuse
|
||||
//! a spelling may read the raw value: they can refuse more, never run something the parse did not
|
||||
//! name.
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::utils::{parse_hub_id, RunnableKind};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct RunnableRef {
|
||||
kind: RunnableKind,
|
||||
path: String,
|
||||
}
|
||||
|
||||
impl RunnableRef {
|
||||
/// A bare path with a separate flag, as the run routes take it.
|
||||
/// One leading `/` is tolerated, as the run routes have always stripped it. A second one is
|
||||
/// refused: a stored path normalized once and stripped again when read must not change meaning.
|
||||
/// A Hub path (`hub/<id>/…`, `hub/flows/<id>/…` for a flow) must carry a positive numeric id.
|
||||
pub fn from_path(path: &str, is_flow: bool) -> Result<Self> {
|
||||
let kind = if is_flow {
|
||||
RunnableKind::Flow
|
||||
} else {
|
||||
RunnableKind::Script
|
||||
};
|
||||
let canonical = path.strip_prefix('/').unwrap_or(path);
|
||||
if canonical.is_empty() || canonical.starts_with('/') {
|
||||
return Err(Error::BadRequest(format!(
|
||||
"invalid {kind} path '{path}': expected a workspace or hub path"
|
||||
)));
|
||||
}
|
||||
let hub_prefix = match kind {
|
||||
RunnableKind::Script => "hub/",
|
||||
RunnableKind::Flow => "hub/flows/",
|
||||
};
|
||||
if canonical.starts_with(hub_prefix) {
|
||||
parse_hub_id(canonical, hub_prefix)?;
|
||||
}
|
||||
Ok(Self { kind, path: canonical.to_string() })
|
||||
}
|
||||
|
||||
pub fn is_flow(&self) -> bool {
|
||||
self.kind == RunnableKind::Flow
|
||||
}
|
||||
|
||||
/// The path without its leading `/`.
|
||||
pub fn path(&self) -> &str {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_every_spelling() {
|
||||
let bare = |s: &str, f: bool| RunnableRef::from_path(s, f);
|
||||
for (name, got, is_flow, path) in [
|
||||
("script", bare("u/me/x", false), false, "u/me/x"),
|
||||
("flow", bare("f/a/b", true), true, "f/a/b"),
|
||||
("one slash", bare("/u/me/x", false), false, "u/me/x"),
|
||||
("hub script", bare("hub/12/x", false), false, "hub/12/x"),
|
||||
("/hub script", bare("/hub/9/x", false), false, "hub/9/x"),
|
||||
(
|
||||
"hub flow",
|
||||
bare("hub/flows/76/x", true),
|
||||
true,
|
||||
"hub/flows/76/x",
|
||||
),
|
||||
// A flow's Hub prefix is `hub/flows/`: `hub/abc` is a workspace flow path.
|
||||
(
|
||||
"hub/ flow not flows/",
|
||||
bare("hub/abc", true),
|
||||
true,
|
||||
"hub/abc",
|
||||
),
|
||||
] {
|
||||
let got = got.unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
assert_eq!((got.is_flow(), got.path()), (is_flow, path), "{name}");
|
||||
}
|
||||
|
||||
for (name, got) in [
|
||||
("empty", bare("", false)),
|
||||
("only a slash", bare("/", false)),
|
||||
("two slashes", bare("//u/me/x", false)),
|
||||
("two slashes hub", bare("//hub/1/x", false)),
|
||||
("hub non-numeric", bare("hub/abc", false)),
|
||||
("hub zero", bare("hub/0/x", false)),
|
||||
("hub flow path as a script", bare("hub/flows/1/x", false)),
|
||||
("hub flow non-numeric", bare("hub/flows/abc", true)),
|
||||
("hub flow zero", bare("hub/flows/0", true)),
|
||||
] {
|
||||
assert!(got.is_err(), "{name}: {got:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -545,11 +545,10 @@ pub async fn check_schema_contracts(
|
||||
let producer_specs: HashMap<String, Option<MaterializeSpec>> = producer_rows
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
(
|
||||
r.path,
|
||||
windmill_parser::asset_parser::parse_pipeline_annotations(&r.content)
|
||||
.materialize,
|
||||
)
|
||||
let spec = windmill_parser::asset_parser::parse_pipeline_annotations(&r.content)
|
||||
.for_script(&r.path)
|
||||
.materialize;
|
||||
(r.path, spec)
|
||||
})
|
||||
.collect();
|
||||
|
||||
|
||||
@@ -6,11 +6,12 @@ use serde_json::value::RawValue;
|
||||
use serde_json::{json, Value};
|
||||
use uuid::Uuid;
|
||||
use windmill_common::error::{to_anyhow, Error, Result};
|
||||
use windmill_common::jobs::JobKind;
|
||||
use windmill_common::utils::sanitize_string_from_password;
|
||||
use windmill_common::worker::{get_memory, to_raw_value, Connection, SqlResultCollectionStrategy};
|
||||
use windmill_common::workspaces::{
|
||||
get_datatable_resource_from_db, get_ducklake_from_db_unchecked,
|
||||
sql_literal_len, strip_fork_reserved_attach_args, strip_sql_comments, DatatableAccess, DatatableConnectAs,
|
||||
get_datatable_resource_from_db, get_ducklake_from_db_unchecked, sql_literal_len,
|
||||
strip_fork_reserved_attach_args, strip_sql_comments, DatatableAccess, DatatableConnectAs,
|
||||
DucklakeCatalogResourceType,
|
||||
};
|
||||
use windmill_common::PgDatabase;
|
||||
@@ -115,6 +116,8 @@ async fn fetch_custom_test_body(conn: &Connection, w_id: &str, path: &str) -> Re
|
||||
// `record_declared_warehouse_write`).
|
||||
fn build_materialized_query(
|
||||
query: &str,
|
||||
// Names the table of a target that names none; a run without a path has to name it.
|
||||
script_path: Option<&str>,
|
||||
partition_value: Option<&str>,
|
||||
// Custom (`// data_test <path>`) test bodies, pre-fetched by the caller
|
||||
// (`fetch_custom_test_bodies`) so this stays pure/sync and unit-testable —
|
||||
@@ -129,6 +132,10 @@ fn build_materialized_query(
|
||||
};
|
||||
|
||||
let ann = parse_pipeline_annotations(query);
|
||||
let ann = match script_path {
|
||||
Some(path) => ann.for_script(path),
|
||||
None => ann,
|
||||
};
|
||||
let has_tests = !ann.data_tests.is_empty();
|
||||
let Some(m) = ann.materialize else {
|
||||
// Data tests run *against the materialized asset*; without a
|
||||
@@ -211,7 +218,8 @@ fn build_materialized_query(
|
||||
}
|
||||
if table.is_empty() {
|
||||
return Err(Error::ExecutionErr(format!(
|
||||
"materialize: target `ducklake://{}` has no table (use ducklake://<name>/<table>)",
|
||||
"materialize: target `ducklake://{}` has no table, and this run has no script path to \
|
||||
name it after (use ducklake://<name>/<table>)",
|
||||
m.target_path
|
||||
)));
|
||||
}
|
||||
@@ -1343,7 +1351,30 @@ pub async fn do_duckdb(
|
||||
// itself stays pure/sync.
|
||||
let custom_test_bodies =
|
||||
fetch_custom_test_bodies(query, conn, &job.workspace_id).await?;
|
||||
build_materialized_query(query, partition_value.as_deref(), &custom_test_bodies)?
|
||||
// A deployed script, run directly or from a flow, names an untabled target after
|
||||
// its own path. An inline flow step's path is `<flow>/<step id>`, which would name
|
||||
// one shared table per step id across every flow, so it has to name its table.
|
||||
// A flow editor's "Test this step" (marked by `_FLOW_PATH`) previews an inline step
|
||||
// under that same `<flow>/<step id>` path. A step referencing a deployed script
|
||||
// sends that script's hash and previews under its own path, which names its table
|
||||
// as the script's own run does, wherever the script sits relative to the flow.
|
||||
let inline_step_preview = job.runnable_id.is_none()
|
||||
&& job
|
||||
.args
|
||||
.as_ref()
|
||||
.is_some_and(|a| a.0.contains_key("_FLOW_PATH"));
|
||||
let script_path = (job.kind == JobKind::Script
|
||||
|| (job.kind == JobKind::Preview
|
||||
&& job.flow_step_id.is_none()
|
||||
&& !inline_step_preview))
|
||||
.then(|| job.runnable_path.as_deref())
|
||||
.flatten();
|
||||
build_materialized_query(
|
||||
query,
|
||||
script_path,
|
||||
partition_value.as_deref(),
|
||||
&custom_test_bodies,
|
||||
)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -3592,7 +3623,7 @@ mod tests {
|
||||
// The wrapped query still references `$file`, so the parsed sig binds it.
|
||||
// No custom data tests here, so no fetched bodies are needed.
|
||||
let (rewritten, _) =
|
||||
build_materialized_query(script, None, &std::collections::HashMap::new())
|
||||
build_materialized_query(script, None, None, &std::collections::HashMap::new())
|
||||
.expect("materialize builds")
|
||||
.expect("materialize present");
|
||||
let rewritten = rewritten.expect("managed mode rewrites the query");
|
||||
@@ -3626,6 +3657,7 @@ mod tests {
|
||||
// binds them at run time.
|
||||
let (rewritten, _) = build_materialized_query(
|
||||
script,
|
||||
None,
|
||||
Some("2026-07-02"),
|
||||
&std::collections::HashMap::new(),
|
||||
)
|
||||
@@ -3648,7 +3680,7 @@ mod tests {
|
||||
let script = "-- materialize ducklake://main/dim key=id history track=name\n\
|
||||
SELECT id, name FROM dl.src";
|
||||
let (rewritten, _) =
|
||||
build_materialized_query(script, None, &std::collections::HashMap::new())
|
||||
build_materialized_query(script, None, None, &std::collections::HashMap::new())
|
||||
.expect("materialize builds")
|
||||
.expect("materialize present");
|
||||
let rewritten = rewritten.expect("scd2 is managed — must rewrite");
|
||||
@@ -3679,7 +3711,7 @@ mod tests {
|
||||
let script = "-- materialize ducklake://main/dim key=id history deletes=close\n\
|
||||
SELECT id, name FROM dl.src";
|
||||
let (rewritten, _) =
|
||||
build_materialized_query(script, None, &std::collections::HashMap::new())
|
||||
build_materialized_query(script, None, None, &std::collections::HashMap::new())
|
||||
.expect("materialize builds")
|
||||
.expect("materialize present");
|
||||
let rewritten = rewritten.expect("scd2 is managed — must rewrite");
|
||||
@@ -3692,10 +3724,11 @@ mod tests {
|
||||
#[test]
|
||||
fn materialize_scd2_requires_key() {
|
||||
let script = "-- materialize scd2 ducklake://main/dim\nSELECT id, name FROM dl.src";
|
||||
let err = match build_materialized_query(script, None, &std::collections::HashMap::new()) {
|
||||
Err(e) => e,
|
||||
Ok(_) => panic!("scd2 without key must error"),
|
||||
};
|
||||
let err =
|
||||
match build_materialized_query(script, None, None, &std::collections::HashMap::new()) {
|
||||
Err(e) => e,
|
||||
Ok(_) => panic!("scd2 without key must error"),
|
||||
};
|
||||
assert!(
|
||||
format!("{err}").contains("requires a natural key"),
|
||||
"got: {err}"
|
||||
@@ -3708,6 +3741,7 @@ mod tests {
|
||||
-- materialize scd2 ducklake://main/dim key=id\nSELECT id, name FROM dl.src";
|
||||
let err = match build_materialized_query(
|
||||
script,
|
||||
None,
|
||||
Some("2026-07-01"),
|
||||
&std::collections::HashMap::new(),
|
||||
) {
|
||||
@@ -3733,7 +3767,7 @@ mod tests {
|
||||
-- data_test not_null id\n\
|
||||
SELECT id FROM dl.src";
|
||||
let (rewritten, meta) =
|
||||
build_materialized_query(script, None, &std::collections::HashMap::new())
|
||||
build_materialized_query(script, None, None, &std::collections::HashMap::new())
|
||||
.expect("materialize builds")
|
||||
.expect("materialize present");
|
||||
let rewritten = rewritten.expect("managed mode rewrites the query");
|
||||
@@ -3758,7 +3792,7 @@ mod tests {
|
||||
let script = "-- materialize ducklake://main/dim key=id on_schema_change=fail\n\
|
||||
SELECT id, name FROM dl.src";
|
||||
let (rewritten, meta) =
|
||||
build_materialized_query(script, None, &std::collections::HashMap::new())
|
||||
build_materialized_query(script, None, None, &std::collections::HashMap::new())
|
||||
.expect("materialize builds")
|
||||
.expect("materialize present");
|
||||
let rewritten = rewritten.expect("managed mode rewrites the query");
|
||||
@@ -3777,7 +3811,7 @@ mod tests {
|
||||
let script = "-- materialize ducklake://main/dim key=id on_schema_change=sync\n\
|
||||
SELECT id, name FROM dl.src";
|
||||
let (rewritten, meta) =
|
||||
build_materialized_query(script, None, &std::collections::HashMap::new())
|
||||
build_materialized_query(script, None, None, &std::collections::HashMap::new())
|
||||
.expect("materialize builds")
|
||||
.expect("materialize present");
|
||||
let rewritten = rewritten.expect("managed mode rewrites the query");
|
||||
@@ -3810,7 +3844,7 @@ mod tests {
|
||||
let script = "-- materialize ducklake://main/dim key=id\n\
|
||||
SELECT id, name FROM dl.src";
|
||||
let (rewritten, meta) =
|
||||
build_materialized_query(script, None, &std::collections::HashMap::new())
|
||||
build_materialized_query(script, None, None, &std::collections::HashMap::new())
|
||||
.expect("materialize builds")
|
||||
.expect("materialize present");
|
||||
let rewritten = rewritten.expect("managed mode rewrites the query");
|
||||
@@ -3834,7 +3868,7 @@ mod tests {
|
||||
let script = "-- materialize ducklake://main/t on_schema_change=fail\n\
|
||||
SELECT a, b FROM dl.src";
|
||||
let (rewritten, meta) =
|
||||
build_materialized_query(script, None, &std::collections::HashMap::new())
|
||||
build_materialized_query(script, None, None, &std::collections::HashMap::new())
|
||||
.expect("materialize builds")
|
||||
.expect("materialize present");
|
||||
let rewritten = rewritten.expect("managed mode rewrites the query");
|
||||
|
||||
+1
-1
@@ -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.856.0";
|
||||
export const VERSION = "v1.858.0";
|
||||
|
||||
export async function login(email: string, password: string): Promise<string> {
|
||||
return await windmill.UserService.login({
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@windmill-labs/chat-sdk",
|
||||
"version": "1.856.0",
|
||||
"version": "1.858.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@windmill-labs/chat-sdk",
|
||||
"version": "1.856.0",
|
||||
"version": "1.858.0",
|
||||
"license": "Apache-2.0",
|
||||
"devDependencies": {
|
||||
"@ai-sdk/react": "^4.0.102",
|
||||
|
||||
@@ -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.856.0",
|
||||
"version": "1.858.0",
|
||||
"author": "Ruben Fiszel",
|
||||
"license": "Apache-2.0",
|
||||
"homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme",
|
||||
|
||||
@@ -173,7 +173,7 @@ export type ParseAssetsRaw = {
|
||||
| { kind: string }
|
||||
)[];
|
||||
// `// materialize [manual] <asset> …` — managed-materialize target (emitted by
|
||||
// the wasm asset parser). The body (a bare trailing SELECT) writes nothing
|
||||
// the wasm asset parser, which does not know the script path: see `withDefaultTable`). The body (a bare trailing SELECT) writes nothing
|
||||
// inferable, so the producer's output edge comes from here, not from `assets`.
|
||||
materialize?: {
|
||||
target_kind: string;
|
||||
@@ -195,6 +195,19 @@ export type ParseAssetsRaw = {
|
||||
column_lineage?: unknown[];
|
||||
};
|
||||
|
||||
type ParsedMaterialize = NonNullable<ParseAssetsRaw["materialize"]>;
|
||||
|
||||
/** Mirrors Rust `MaterializeSpec::resolve_table`: a DuckLake target naming no table writes
|
||||
* `<lake>/<script name>`, with every character DuckDB would need quoted replaced by `_`. */
|
||||
export function withDefaultTable(m: ParsedMaterialize, scriptPath: string): ParsedMaterialize {
|
||||
// `<lake>/<table>` and `<lake>.<table>` already name a table.
|
||||
if (m.target_kind !== "ducklake" || /[/.]/.test(m.target_path)) return m;
|
||||
const name = (scriptPath.split("/").pop() ?? "").trim().replace(/[^A-Za-z0-9_]/gu, "_");
|
||||
// The generated SQL names the table unquoted, so it cannot start with a digit.
|
||||
const table = /^[0-9]/.test(name) ? `_${name}` : name;
|
||||
return table ? { ...m, target_path: `${m.target_path}/${table}` } : m;
|
||||
}
|
||||
|
||||
// Mirror `inferAssets` (frontend/src/lib/infer.ts): only ts / py / sql have a
|
||||
// wasm asset parser. SQL dialects all route to `parse_assets_sql` — the comment-
|
||||
// header annotation scan inside it is dialect-independent, so `in_pipeline` /
|
||||
@@ -367,6 +380,43 @@ const MUTE_ASSET_PREFIXES: [string, string][] = [
|
||||
["volume://", "volume"],
|
||||
];
|
||||
|
||||
/**
|
||||
* A `materialize` header line naming no target (`-- materialize`, `-- materialize key=id`,
|
||||
* `-- materialize scd2 key=id`), which wasm asset parsers older than the default-table rule
|
||||
* drop. Mirrors Rust `parse_materialize_spec`; a line naming a target is left to the parser,
|
||||
* and `manual` has to name one.
|
||||
*/
|
||||
export function recoverBareMaterialize(content: string): ParsedMaterialize | undefined {
|
||||
for (const rawLine of content.split("\n")) {
|
||||
const line = rawLine.trimStart();
|
||||
if (line === "") continue;
|
||||
let rest: string;
|
||||
if (line.startsWith("//") || line.startsWith("--")) rest = line.slice(2);
|
||||
else if (line.startsWith("#")) rest = line.slice(1);
|
||||
else break;
|
||||
const m = rest.trim().match(/^materialize(?:\s+(.*))?$/);
|
||||
if (!m) continue;
|
||||
let tokens = (m[1] ?? "").split(/\s+/).filter((t) => t !== "");
|
||||
if (tokens[0] === "manual") return undefined;
|
||||
const scd2Keyword = tokens[0] === "scd2";
|
||||
if (scd2Keyword) tokens = tokens.slice(1);
|
||||
const first = tokens[0] ?? "";
|
||||
const namesTarget =
|
||||
first.includes("://") ||
|
||||
(first !== "" && first !== "append" && first !== "history" && !first.includes("="));
|
||||
if (namesTarget) return undefined;
|
||||
const key = tokens.find((t) => t.startsWith("key="))?.slice("key=".length);
|
||||
return {
|
||||
target_kind: "ducklake",
|
||||
target_path: "main",
|
||||
...(tokens.includes("append") ? { append: true } : {}),
|
||||
...(key ? { unique_key: key } : {}),
|
||||
...(scd2Keyword || tokens.includes("history") ? { scd2: true } : {}),
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// `// mute <asset>` / `// mute all` from the LEADING comment header, as
|
||||
// `<kind>:<path>` keys. Parsed locally because the pinned wasm asset parser
|
||||
// predates the mute annotations; mirrors the canonical parsers (Rust
|
||||
@@ -715,7 +765,8 @@ export async function buildLocalPipelineGraph(args: {
|
||||
// Carry the parsed `// tag` so previews route to the same worker the
|
||||
// deployed pipeline would (both `pipeline run --local` and `/pipeline_dev`).
|
||||
pipelineScripts.push(out.tag ? { ...s, tag: out.tag } : s);
|
||||
const mat = out.materialize;
|
||||
const parsedMat = out.materialize ?? recoverBareMaterialize(s.content);
|
||||
const mat = parsedMat && withDefaultTable(parsedMat, s.path);
|
||||
// Managed-materialize write strategy, derived like the deployed graph —
|
||||
// precedence mirrors the runtime: scd2 (`history`) > append > merge
|
||||
// (key=<col>) > replace. Manual mode has no managed strategy.
|
||||
|
||||
@@ -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.856.0";
|
||||
export const VERSION = "1.858.0";
|
||||
|
||||
Generated
+11
-3
@@ -8340,7 +8340,11 @@ The key must be a **string literal** — the graph parser is static and cannot f
|
||||
>
|
||||
> 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.
|
||||
|
||||
A 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.) Write strategy:
|
||||
A 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.)
|
||||
|
||||
A 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.
|
||||
|
||||
Write strategy:
|
||||
|
||||
- no option → **replace** the whole table each run (full refresh; the only mode whose output columns may change);
|
||||
- \`// materialize <uri> append\` → INSERT-append rows (incremental);
|
||||
@@ -8371,7 +8375,8 @@ On a node that materializes a DuckLake table, \`// measure <name> = <aggregate>
|
||||
2. 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.
|
||||
3. Start each body with \`// pipeline\`, then the \`// on\` input declarations, then the transform that writes the output.
|
||||
4. **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.
|
||||
5. Don't deploy nodes unless the user asks to. A pipeline only "runs" once its scripts are deployed and their triggers exist.
|
||||
5. 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.
|
||||
6. Don't deploy nodes unless the user asks to. A pipeline only "runs" once its scripts are deployed and their triggers exist.
|
||||
|
||||
Locally:
|
||||
|
||||
@@ -8397,9 +8402,12 @@ Node \`f/sales/orders_daily\` (runs when \`orders\` is produced, writes a rollup
|
||||
-- pipeline
|
||||
-- on ducklake://main/orders
|
||||
-- materialize ducklake://main/orders_daily
|
||||
ATTACH 'ducklake://main' AS lake;
|
||||
SELECT date_trunc('day', ts) AS day, count(*) AS n
|
||||
FROM ducklake.main.orders GROUP BY 1
|
||||
FROM lake.orders GROUP BY 1
|
||||
\`\`\`
|
||||
|
||||
A 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.
|
||||
`,
|
||||
"datatables": `---
|
||||
name: datatables
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
buildLocalPipelineGraph,
|
||||
hideDbtRunnables,
|
||||
parseMuteAnnotations,
|
||||
recoverBareMaterialize,
|
||||
withDefaultTable,
|
||||
} from "../src/commands/pipeline/localGraph.ts";
|
||||
|
||||
// Build a throwaway workspace tree with `f/<folder>/<file>` scripts and a
|
||||
@@ -112,6 +114,40 @@ test("empty / no-pipeline folder yields an empty graph", async () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("recoverBareMaterialize reads the target-less forms the Rust parser accepts", () => {
|
||||
expect(recoverBareMaterialize("-- pipeline\n-- materialize scd2 key=id\nSELECT 1")).toEqual({
|
||||
target_kind: "ducklake",
|
||||
target_path: "main",
|
||||
unique_key: "id",
|
||||
scd2: true,
|
||||
});
|
||||
expect(recoverBareMaterialize("-- materialize manual")).toBeUndefined();
|
||||
expect(recoverBareMaterialize("-- materialize ducklake://main/x")).toBeUndefined();
|
||||
});
|
||||
|
||||
test("a bare `-- materialize` producer writes the table named after it", async () => {
|
||||
await withFolder(
|
||||
{
|
||||
"users.duckdb.sql": `-- pipeline\n-- materialize key=id\nSELECT 1 AS id;\n`,
|
||||
"consume.duckdb.sql":
|
||||
`-- pipeline\n-- on ducklake://main/users\nSELECT count(*) FROM users;\n`,
|
||||
},
|
||||
async (root, folder) => {
|
||||
const { graph } = await buildLocalPipelineGraph({ root, folder, defaultTs: "bun" });
|
||||
const users = graph.runnables.find((r) => r.path === "f/mypipe/users");
|
||||
expect(users?.materialize_target).toEqual({ kind: "ducklake", path: "main/users" });
|
||||
expect(users?.materialize_strategy).toBe("merge");
|
||||
expect(graph.edges).toContainEqual({
|
||||
runnable_kind: "script",
|
||||
runnable_path: "f/mypipe/users",
|
||||
asset_kind: "ducklake",
|
||||
asset_path: "main/users",
|
||||
access_type: "w",
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("`// materialize <asset>` producer connects to its `// on` consumer", async () => {
|
||||
// The wasm asset parser doesn't surface `// materialize`; the CLI-side scan
|
||||
// must still emit the producer's write edge so it links to the consumer.
|
||||
@@ -1009,3 +1045,19 @@ test("hideDbtRunnables is a no-op when the folder has no dbt project", () => {
|
||||
};
|
||||
expect(hideDbtRunnables(g)).toBe(g);
|
||||
});
|
||||
|
||||
// Mirrors the Rust `materialize_without_table_is_named_after_the_script` test: the wasm
|
||||
// parser hands over the lake alone, and the local graph names the table as deploy does.
|
||||
test("withDefaultTable names an untabled DuckLake target after the script", () => {
|
||||
const lakeOnly = { target_kind: "ducklake", target_path: "main" };
|
||||
expect(withDefaultTable(lakeOnly, "f/shop/orders-daily").target_path).toBe(
|
||||
"main/orders_daily",
|
||||
);
|
||||
// One `_` per character, as the Rust rule counts them, whatever its width.
|
||||
expect(withDefaultTable(lakeOnly, "f/shop/orders_𐐀").target_path).toBe("main/orders__");
|
||||
for (const target_path of ["main/orders", "main.orders"]) {
|
||||
expect(
|
||||
withDefaultTable({ target_kind: "ducklake", target_path }, "f/shop/x").target_path,
|
||||
).toBe(target_path);
|
||||
}
|
||||
});
|
||||
|
||||
+2
-1
@@ -196,7 +196,8 @@ services:
|
||||
- DEBUGGER_PORT=3003 # Debugger service port
|
||||
- ENABLE_NSJAIL=false # Set to true for nsjail sandboxing (requires privileged: true)
|
||||
- REQUIRE_SIGNED_DEBUG_REQUESTS=true # Require backend-signed JWT tokens for debug sessions. Do NOT set to false on any internet-reachable deployment: it exposes an unauthenticated code-execution debugger.
|
||||
- WINDMILL_BASE_URL=http://windmill_server:8000
|
||||
- WINDMILL_BASE_URL=http://windmill_server:8000 # Needed to verify the backend-signed tokens the LSP, debugger and multiplayer require
|
||||
# - REQUIRE_SIGNED_LSP_REQUESTS=false # Only for a windmill_server older than this image, which cannot sign LSP sessions
|
||||
# - DEBUG_ALLOWED_ORIGINS=https://your-windmill-host # Optional CSWSH hardening: comma-separated allowlist of browser Origins permitted to open debug WebSockets
|
||||
volumes:
|
||||
- lsp_cache:/pyls/.cache
|
||||
|
||||
@@ -13,8 +13,8 @@
|
||||
# Build:
|
||||
# docker build -f docker/DockerfileExtra -t windmill-extra .
|
||||
#
|
||||
# Run:
|
||||
# docker run -p 3001:3001 -p 3002:3002 -p 3003:3003 windmill-extra
|
||||
# Run (the gateway on 3000 fronts all three; the LSP port is bound to localhost):
|
||||
# docker run -p 3000:3000 -e WINDMILL_BASE_URL=http://windmill_server:8000 windmill-extra
|
||||
|
||||
# ============================================================================
|
||||
# Build final extra services image from windmill-ee-slim (includes nsjail)
|
||||
@@ -113,6 +113,7 @@ COPY multiplayer/package.json .
|
||||
COPY multiplayer/package-lock.json .
|
||||
COPY multiplayer/server.mjs .
|
||||
COPY multiplayer/gateway.mjs .
|
||||
COPY multiplayer/jwt.mjs .
|
||||
|
||||
# Install dependencies
|
||||
RUN npm ci --omit=dev
|
||||
|
||||
@@ -145,9 +145,20 @@ echo "[entrypoint] ENABLE_GATEWAY=${ENABLE_GATEWAY:-true}"
|
||||
|
||||
# Start LSP service
|
||||
if [ "${ENABLE_LSP:-true}" = "true" ]; then
|
||||
echo "[entrypoint] Starting LSP on port ${LSP_PORT:-3001}..."
|
||||
cd /pyls
|
||||
PORT=${LSP_PORT:-3001} python3 pyls_launcher.py &
|
||||
# Only the gateway, which checks the signed tokens, may reach the launcher. The gateway
|
||||
# then also serves LSP_PORT, which proxies set up before it existed still point at.
|
||||
LSP_HOST=0.0.0.0
|
||||
LSP_LAUNCHER_PORT=${LSP_PORT:-3001}
|
||||
if [ "${ENABLE_GATEWAY:-true}" = "true" ]; then
|
||||
LSP_HOST=127.0.0.1
|
||||
LSP_LAUNCHER_PORT=${LSP_INTERNAL_PORT:-3004}
|
||||
else
|
||||
echo "[entrypoint] WARNING: ENABLE_GATEWAY=false: the language servers are served on" \
|
||||
"port ${LSP_PORT:-3001} without the signed-token check the gateway applies" >&2
|
||||
fi
|
||||
echo "[entrypoint] Starting LSP on $LSP_HOST:$LSP_LAUNCHER_PORT..."
|
||||
PORT=$LSP_LAUNCHER_PORT LSP_HOST=$LSP_HOST python3 pyls_launcher.py &
|
||||
PIDS+=($!)
|
||||
NAMES+=("LSP")
|
||||
echo "[entrypoint] LSP started (PID: ${PIDS[-1]})"
|
||||
@@ -187,7 +198,11 @@ fi
|
||||
if [ "${ENABLE_GATEWAY:-true}" = "true" ]; then
|
||||
echo "[entrypoint] Starting Gateway on port ${GATEWAY_PORT:-3000}..."
|
||||
cd /multiplayer
|
||||
PORT=${GATEWAY_PORT:-3000} node gateway.mjs &
|
||||
GATEWAY_LSP_ARGS=()
|
||||
if [ "${ENABLE_LSP:-true}" = "true" ]; then
|
||||
GATEWAY_LSP_ARGS=(LSP_PORT="$LSP_LAUNCHER_PORT" GATEWAY_LEGACY_LSP_PORT="${LSP_PORT:-3001}")
|
||||
fi
|
||||
env PORT="${GATEWAY_PORT:-3000}" "${GATEWAY_LSP_ARGS[@]}" node gateway.mjs &
|
||||
PIDS+=($!)
|
||||
NAMES+=("Gateway")
|
||||
echo "[entrypoint] Gateway started (PID: ${PIDS[-1]})"
|
||||
|
||||
@@ -11,6 +11,13 @@ Symbols, not line numbers, are cited: they drift less.
|
||||
- **Sessions** are `token` rows with `label='session'` plus the HttpOnly `token` cookie, minted only
|
||||
by `create_session_token` (`windmill-api-users/src/users.rs`). `GET /api/users/refresh_token`
|
||||
mints one for any non-job token but returns plain text, no redirect.
|
||||
- **The readable `wm_session` cookie** is a hint of the session (a salted hash of the token, so it
|
||||
grants nothing), mirrored onto every response that sets or clears `token`, by middleware
|
||||
(`windmill-api/src/session_hint.rs`) rather than at each cookie site, so a new site gets it
|
||||
for free. The frontend renders a reload as the user `whoami` last confirmed only while the
|
||||
hint still matches the one stored with them (`frontend/src/lib/lastSession.ts`): logout,
|
||||
expiry or another login changes or drops it. A session revoked server-side keeps its hint,
|
||||
so until `whoami` answers that browser still renders as its own last user.
|
||||
- **`tokens/impersonate`** (superadmin) returns a multi-use token and sets no cookie.
|
||||
- **`max_token_expiration_days`** caps `POST /users/tokens/create` and `tokens/impersonate`, by
|
||||
shortening the stored expiration (`cap_token_expiration`), never by refusing: the CLI
|
||||
|
||||
+6
-12
@@ -87,18 +87,12 @@ The default proxy is setup to use the remote backend: <https://app.windmill.dev>
|
||||
You can configure another proxy to use like so:
|
||||
|
||||
```bash
|
||||
REMOTE=http://127.0.0.1:8000 REMOTE_LSP=http://127.0.0.1:3001 npm run dev
|
||||
REMOTE=http://127.0.0.1:8000 npm run dev
|
||||
```
|
||||
|
||||
`REMOTE_LSP` needs a language server on port 3001. The `windmill-extra` image serves one:
|
||||
|
||||
```bash
|
||||
docker run --rm -p 3001:3001 ghcr.io/windmill-labs/windmill-extra:latest
|
||||
```
|
||||
|
||||
To proxy multiplayer and the debugger as well, publish the image's gateway on port 3000 and use `REMOTE_EXTRA`, which
|
||||
covers `/ws/*`, `/ws_mp/*` and `/ws_debug/*`. Those two services verify tokens signed by your backend, so give the
|
||||
container its URL (on Linux, add `--add-host=host.docker.internal:host-gateway`):
|
||||
The language servers, multiplayer and the debugger are served by the `windmill-extra` image behind its gateway on
|
||||
port 3000, proxied with `REMOTE_EXTRA` for `/ws/*`, `/ws_mp/*` and `/ws_debug/*`. All three verify tokens signed by
|
||||
your backend, so give the container its URL (on Linux, add `--add-host=host.docker.internal:host-gateway`):
|
||||
|
||||
```bash
|
||||
docker run --rm -p 3000:3000 -e WINDMILL_BASE_URL=http://host.docker.internal:8000 ghcr.io/windmill-labs/windmill-extra:latest
|
||||
@@ -136,7 +130,7 @@ docker compose up db windmill_server windmill_worker
|
||||
```
|
||||
|
||||
```bash
|
||||
REMOTE=http://localhost REMOTE_LSP=http://localhost npm run dev
|
||||
REMOTE=http://localhost REMOTE_EXTRA=http://localhost npm run dev
|
||||
```
|
||||
|
||||
#### 2. Backend is run by docker, but built from the local source code
|
||||
@@ -190,7 +184,7 @@ DATABASE_URL=postgres://postgres:changeme@127.0.0.1:5433/windmill?sslmode=disabl
|
||||
In the frontend folder:
|
||||
|
||||
```bash
|
||||
REMOTE=http://127.0.0.1:8000 REMOTE_LSP=http://127.0.0.1:3001 npm run dev
|
||||
REMOTE=http://127.0.0.1:8000 REMOTE_EXTRA=http://127.0.0.1:3000 npm run dev
|
||||
```
|
||||
|
||||
**Known issue on M1 Mac while running `cargo run`**
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@windmill-labs/components",
|
||||
"version": "1.856.0",
|
||||
"version": "1.858.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@windmill-labs/components",
|
||||
"version": "1.856.0",
|
||||
"version": "1.858.0",
|
||||
"hasInstallScript": true,
|
||||
"license": "AGPL-3.0",
|
||||
"dependencies": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@windmill-labs/components",
|
||||
"version": "1.856.0",
|
||||
"version": "1.858.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",
|
||||
|
||||
Vendored
+2
@@ -9,6 +9,8 @@ declare namespace App {
|
||||
}
|
||||
|
||||
declare var __pkg__: { version: string }
|
||||
/** The readable session-hint cookie's name: `wm_session`, renamed per backend in dev (vite.config.js). */
|
||||
declare var __WM_SESSION_HINT__: string
|
||||
|
||||
declare module 'svelte-highlight/languages/json'
|
||||
declare module 'svelte-highlight/languages/python'
|
||||
|
||||
+145
-2
@@ -7,7 +7,15 @@
|
||||
<meta name="theme-color" media="(prefers-color-scheme: light)" content="#fbfbfd" />
|
||||
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#3b4252" />
|
||||
<meta name="mobile-web-app-capable" content="yes" />
|
||||
<style type="text/css">
|
||||
<style type="text/css" data-wm-shell>
|
||||
html[data-wm-home-snapshot] #svelte-global-loader {
|
||||
display: none;
|
||||
}
|
||||
#wm-home-snapshot * {
|
||||
animation: none !important;
|
||||
transition: none !important;
|
||||
}
|
||||
|
||||
.st2 {
|
||||
fill: #bcd4fc;
|
||||
}
|
||||
@@ -197,9 +205,95 @@
|
||||
})()
|
||||
</script>
|
||||
%sveltekit.head%
|
||||
<script id="wm-home-snapshot-head">
|
||||
// A reload of Home paints the last rendered Home (homeSnapshot.ts) in place of the splash
|
||||
// while the app boots. Bound like the optimistic render (lastSession.ts): only under the
|
||||
// session hint it was saved with, else it is dropped, so the next person on a shared
|
||||
// browser never sees it; only for the workspace this load opens, at the width and theme
|
||||
// it was rendered at. Its stylesheets are content-hashed files of the build it was saved
|
||||
// by, hence the build check; they are written by the parser so they block the first
|
||||
// paint as the build's own would, and one failing to load drops the snapshot.
|
||||
;(function () {
|
||||
var KEY = 'wm-home-snapshot'
|
||||
var s
|
||||
function drop() {
|
||||
window.__wmHomeSnapshot = undefined
|
||||
document.documentElement.removeAttribute('data-wm-home-snapshot')
|
||||
var shot = document.getElementById('wm-home-snapshot')
|
||||
if (shot) shot.remove()
|
||||
try {
|
||||
localStorage.removeItem(KEY)
|
||||
} catch (_) {}
|
||||
}
|
||||
// Every other page, the public apps included, pays nothing for it.
|
||||
if (location.pathname !== '/' || window.parent !== window) return
|
||||
try {
|
||||
var raw = localStorage.getItem(KEY)
|
||||
if (!raw) return
|
||||
s = JSON.parse(raw)
|
||||
var hint
|
||||
document.cookie.split(/;\s*/).forEach(function (c) {
|
||||
var eq = c.indexOf('=')
|
||||
if (eq > 0 && c.slice(0, eq) === s.cookie) hint = c.slice(eq + 1)
|
||||
})
|
||||
var age = Date.now() - s.savedAt
|
||||
if (
|
||||
s.format !== 1 ||
|
||||
s.build !== '%sveltekit.version%' ||
|
||||
!hint ||
|
||||
hint !== s.hint ||
|
||||
!(age >= 0 && age < 7 * 24 * 3600 * 1000)
|
||||
)
|
||||
return drop()
|
||||
var params = new URLSearchParams(location.search)
|
||||
var other = false
|
||||
params.forEach(function (_, k) {
|
||||
if (k !== 'workspace') other = true
|
||||
})
|
||||
// The workspace the app opens, as stores.ts and the (logged) layout pick it.
|
||||
var ws = params.get('workspace')
|
||||
if (ws === null) ws = sessionStorage.getItem('workspace')
|
||||
if (ws === null) ws = localStorage.getItem('workspace')
|
||||
var mode = localStorage.getItem('dark-mode')
|
||||
var dark =
|
||||
mode !== null ? mode === 'dark' : matchMedia('(prefers-color-scheme: dark)').matches
|
||||
if (other || ws !== s.workspace || innerWidth !== s.width || dark !== s.dark) return
|
||||
} catch (_) {
|
||||
return
|
||||
}
|
||||
var html = document.documentElement
|
||||
html.setAttribute('data-wm-home-snapshot', '')
|
||||
;['dark', 'github-dark'].forEach(function (c) {
|
||||
html.classList.toggle(c, (' ' + s.htmlClass + ' ').indexOf(' ' + c + ' ') !== -1)
|
||||
})
|
||||
document.addEventListener(
|
||||
'error',
|
||||
function (e) {
|
||||
var t = e.target
|
||||
if (t && t.tagName === 'LINK' && t.hasAttribute('data-wm-home-snapshot')) drop()
|
||||
},
|
||||
true
|
||||
)
|
||||
var links = ''
|
||||
s.stylesheets.forEach(function (href) {
|
||||
links +=
|
||||
'<link rel="stylesheet" data-wm-home-snapshot href="' +
|
||||
String(href).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<') +
|
||||
'">'
|
||||
})
|
||||
document.write(links)
|
||||
s.styles.forEach(function (css) {
|
||||
var style = document.createElement('style')
|
||||
style.setAttribute('data-wm-home-snapshot', '')
|
||||
style.textContent = css
|
||||
document.head.appendChild(style)
|
||||
})
|
||||
window.__wmHomeSnapshot = s
|
||||
})()
|
||||
</script>
|
||||
</head>
|
||||
<body data-sveltekit-preload-code="viewport" class="outline-none focus:outline-none">
|
||||
<div style="display: contents">
|
||||
<div id="wm-app" style="display: contents">
|
||||
<div id="svelte-global-loader">
|
||||
<div id="mainbg" style="position: absolute; bottom: 0; left: 0; width: 100%; height: 100vh">
|
||||
</div>
|
||||
@@ -259,6 +353,55 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script id="wm-home-snapshot-body">
|
||||
// The snapshot the head script accepted. Not interactive: its content is inert, and the
|
||||
// cover above it takes the pointer until the live Home replaces it (homeSnapshot.ts).
|
||||
// A boot that never gets there gives the splash back.
|
||||
;(function () {
|
||||
var s = window.__wmHomeSnapshot
|
||||
if (!s) return
|
||||
try {
|
||||
var shot = document.createElement('div')
|
||||
shot.id = 'wm-home-snapshot'
|
||||
shot.setAttribute('aria-hidden', 'true')
|
||||
shot.style.cssText =
|
||||
'position:fixed;inset:0;z-index:2147483647;overflow:hidden;cursor:progress'
|
||||
shot.style.background = s.background
|
||||
var parsed = new DOMParser().parseFromString(s.html, 'application/xhtml+xml')
|
||||
if (parsed.getElementsByTagName('parsererror').length) {
|
||||
document.documentElement.removeAttribute('data-wm-home-snapshot')
|
||||
try {
|
||||
localStorage.removeItem('wm-home-snapshot')
|
||||
} catch (_) {}
|
||||
return
|
||||
}
|
||||
// Cleaned again here, not only when saved: anything that can write this origin's
|
||||
// storage once could otherwise plant markup that runs on every load of Home.
|
||||
var executable =
|
||||
/^(script|iframe|frame|object|embed|link|meta|base|form|animate|set|animatemotion|animatetransform)$/i
|
||||
Array.prototype.forEach.call(parsed.querySelectorAll('*'), function (el) {
|
||||
if (executable.test(el.localName)) return el.remove()
|
||||
Array.prototype.slice.call(el.attributes).forEach(function (a) {
|
||||
var v = a.value.replace(/[\u0000-\u0020]/g, '')
|
||||
if (/^on/i.test(a.name) || /^(javascript|vbscript):/i.test(v))
|
||||
el.removeAttribute(a.name)
|
||||
})
|
||||
})
|
||||
var content = document.importNode(parsed.documentElement, true)
|
||||
content.setAttribute('inert', '')
|
||||
content.style.height = '100%'
|
||||
shot.appendChild(content)
|
||||
var loader = document.getElementById('svelte-global-loader')
|
||||
loader.parentNode.insertBefore(shot, loader.nextSibling)
|
||||
setTimeout(function () {
|
||||
shot.remove()
|
||||
document.documentElement.removeAttribute('data-wm-home-snapshot')
|
||||
}, 15000)
|
||||
} catch (_) {
|
||||
document.documentElement.removeAttribute('data-wm-home-snapshot')
|
||||
}
|
||||
})()
|
||||
</script>
|
||||
%sveltekit.body%
|
||||
</div>
|
||||
</body>
|
||||
|
||||
@@ -448,6 +448,25 @@ input[type='time']::-webkit-calendar-picker-indicator {
|
||||
}
|
||||
}
|
||||
|
||||
/* Content arriving, rather than being there: Home's page and the page header's actions, which
|
||||
appear only once the header has measured them and so land after what is around them. */
|
||||
@keyframes wm-page-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
.wm-page-in {
|
||||
animation: wm-page-in 500ms ease-out both;
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.wm-page-in {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
.svelte-flow__edges {
|
||||
z-index: -10;
|
||||
}
|
||||
|
||||
@@ -14,16 +14,10 @@
|
||||
interface Props {
|
||||
expressOAuthSetup?: boolean
|
||||
workspace?: string
|
||||
disableChatOffset?: boolean
|
||||
native?: NativeConnect
|
||||
}
|
||||
|
||||
let {
|
||||
expressOAuthSetup = false,
|
||||
workspace = undefined,
|
||||
disableChatOffset = false,
|
||||
native = undefined
|
||||
}: Props = $props()
|
||||
let { expressOAuthSetup = false, workspace = undefined, native = undefined }: Props = $props()
|
||||
|
||||
/** Set by `open(rt, fillPath)`, not by the parent: which resource this run fills is a
|
||||
* property of the click, and a prop would go stale between two different rows. */
|
||||
@@ -82,7 +76,6 @@
|
||||
dispatch('close')
|
||||
}}
|
||||
size="700px"
|
||||
{disableChatOffset}
|
||||
>
|
||||
<DrawerContent
|
||||
title={native?.title ?? addResourceTitle(step > 1 ? resourceType : undefined)}
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
<script lang="ts" module>
|
||||
import { lazyModule } from '$lib/lazyModule.svelte'
|
||||
|
||||
// Its AI review reaches the AI clients, which a list of rows must not load to render.
|
||||
const diffDrawerModule = lazyModule(() => import('./DiffDrawer.svelte'))
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
/**
|
||||
* Home-page draft badge with per-user initial circles. Hover popover lists
|
||||
@@ -10,7 +17,8 @@
|
||||
import Tooltip from './meltComponents/Tooltip.svelte'
|
||||
import { Badge } from './common'
|
||||
import Button from './common/button/Button.svelte'
|
||||
import DiffDrawer from './DiffDrawer.svelte'
|
||||
import type DiffDrawer from './DiffDrawer.svelte'
|
||||
import { tick } from 'svelte'
|
||||
import MigrateLegacyDraftModal from './common/confirmationModal/MigrateLegacyDraftModal.svelte'
|
||||
import { GitCompareArrows, Pencil, Wrench } from 'lucide-svelte'
|
||||
import { DraftService, type UserDraftItemKind } from '$lib/gen'
|
||||
@@ -169,8 +177,10 @@
|
||||
try {
|
||||
const [draftValue, deployed] = await Promise.all([
|
||||
fetchDraft(owner),
|
||||
fetchDeployedValueForDiff(workspace, itemKind, path)
|
||||
fetchDeployedValueForDiff(workspace, itemKind, path),
|
||||
diffDrawerModule.load()
|
||||
])
|
||||
await tick()
|
||||
// Close the popover so it doesn't render over the drawer.
|
||||
popoverOpen = false
|
||||
diffDrawer?.openDrawer()
|
||||
@@ -376,8 +386,9 @@
|
||||
<!-- Only reachable from the popover's "View Diff", which requires `actionsEnabled`.
|
||||
Mounting it unconditionally would put a hidden drawer (portal + effects) on
|
||||
every row of unpaginated lists like resources and variables. -->
|
||||
{#if actionsEnabled}
|
||||
<DiffDrawer bind:this={diffDrawer} isFlow={itemKind === 'flow'} />
|
||||
{#if actionsEnabled && diffDrawerModule.current}
|
||||
{@const LoadedDiffDrawer = diffDrawerModule.current.default}
|
||||
<LoadedDiffDrawer bind:this={diffDrawer} isFlow={itemKind === 'flow'} />
|
||||
{/if}
|
||||
|
||||
{#if workspace && itemKind && path}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user